Spaces:
Sleeping
Sleeping
Pyae Sone commited on
Commit ·
11b240f
1
Parent(s): bbdf1be
feat: God Agent OS v9 — Space-Role Architecture
Browse files- Agent Kernel: replaces GodAgentOrchestratorV7 with generalized kernel
- 8 Spaces: Core, Browser, Sandbox, Coding, Vision, Debug, Deploy, Communication
- 5 Roles: Cognition, Automation, Execution, Repair, Visual Intelligence
- New frontend: Space-Role UI with connectors panel, spaces visualization
- Dashboard: real-time Space activation, role indicator, chat interface
- TopBar: 'Powered by Pyae Sone' branding
- HuggingFace Dockerfile.hf + README.md for HF Space deployment
- Vercel: vercel.json with API proxy to HF backend
- GitHub Actions: auto-deploy workflow
- Backward compatible with v8 16-agent fleet
Powered by Pyae Sone
Files changed (36)
- .github/workflows/deploy.yml+41-111
- backend/Dockerfile.hf+14-23
- backend/README.md+34-43
- backend/api/routes/health.py+8-2
- backend/kernel/__init__.pyAdded+1
- backend/kernel/agent_kernel.pyAdded+331
- backend/main_v9.pyAdded+430
- backend/spaces/__init__.pyAdded+21
- backend/spaces/base_space.pyAdded+91
- backend/spaces/browser_space.pyAdded+104
- backend/spaces/coding_space.pyAdded+106
- backend/spaces/communication_space.pyAdded+106
- backend/spaces/core_space.pyAdded+48
- backend/spaces/debug_space.pyAdded+120
- backend/spaces/deploy_space.pyAdded+109
- backend/spaces/sandbox_space.pyAdded+178
- backend/spaces/vision_space.pyAdded+80
- frontend/app/layout.tsx+2-2
- frontend/app/page.tsx+59-11
- frontend/components/chat/ChatPanel.tsx+8-1
- frontend/components/dashboard/ActivityFeed.tsx+1-1
- frontend/components/dashboard/AgentFleetCard.tsx+1-1
- frontend/components/dashboard/GodModeCard.tsx+2-1
- frontend/components/dashboard/SystemResources.tsx+1-1
- frontend/components/pages/AgentsPage.tsx+11-1
- frontend/components/pages/ConnectorsPage.tsxAdded+224
- frontend/components/pages/DashboardPage.tsx+423-88
- frontend/components/pages/SpacesPage.tsxAdded+267
- frontend/components/pages/TasksPage.tsx+2-1
- frontend/components/shared/Sidebar.tsx+100-120
- frontend/components/shared/TopBar.tsx+76-163
- frontend/lib/api.ts+27-134
- frontend/next.config.js+21-8
- frontend/package-lock.json+4-4
- frontend/store/useAppStore.ts+70-117
- frontend/vercel.json+12-9
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143name: 🚀 God Agent OS v8 — Auto Deployon:push:branches: [master, main]workflow_dispatch:env:HF_SPACE: PYAE1994/autonomous-coding-systemVERCEL_PROJECT: god-agent-osjobs:# ── Build & Syntax Check ──────────────────────────────────────────────────build-check:name: ✅ Build Checkruns-on: ubuntu-lateststeps:- uses: actions/checkout@v4- name: Setup Pythonuses: actions/setup-python@v5with:python-version: '3.11'cache: 'pip'- name: Install backend depsrun: |cd backendpip install -r requirements.txt- name: Syntax check backend (v8)run: |cd backendpython -m py_compile main_v8.pypython -m py_compile ai_router/router_v8.pypython -m py_compile ai_router/key_pool.pypython -m py_compile agents/orchestrator_v7.pypython -m py_compile agents/browser_agent.pypython -m py_compile agents/file_agent.pypython -m py_compile agents/git_agent.pypython -m py_compile agents/test_agent.pypython -m py_compile agents/vision_agent.pyecho "✅ All Python syntax checks passed"- name: Setup Node.jsuses: actions/setup-node@v4with:node-version: '20'cache: 'npm'cache-dependency-path: frontend/package-lock.json- name: Install frontend depsrun: cd frontend && npm ci- name: Build frontendrun: cd frontend && npm run buildenv:NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL || 'https://PYAE1994-autonomous-coding-system.hf.space' }}# ── Deploy to Hugging Face Spaces ────────────────────────────────────────deploy-huggingface:name: 🤗 Deploy to HF Spacesruns-on: ubuntu-latestneeds: build-checkif: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'steps:- uses: actions/checkout@v4with:fetch-depth: 0lfs: true- name: Setup Git for HFrun: |git config --global user.email "action@github.com"git config --global user.name "God Agent CI"- name: Deploy backend to HF Space (v8)env:HF_TOKEN: ${{ secrets.HF_TOKEN }}run: |pip install huggingface_hub -qgit clone https://pyae1994:$HF_TOKEN@huggingface.co/spaces/PYAE1994/autonomous-coding-system /tmp/hf-space# Copy backend filescp -r backend/. /tmp/hf-space/# Use v8 Dockerfilecp backend/Dockerfile.hf /tmp/hf-space/Dockerfile# Create HF README with v8 metadatacat > /tmp/hf-space/README.md << 'EOF'---title: God Agent OS v8emoji: 🤖colorFrom: indigocolorTo: purplesdk: dockerapp_port: 7860pinned: truelicense: mitshort_description: Autonomous Engineering OS v8 — KeyPool Multi-API (Gemini + SambaNova)---# 🤖 God Agent OS v8**KeyPool Multi-API Routing — Gemini + SambaNova Primary LLMs**16-agent autonomous engineering OS with intelligent key pooling.EOFcd /tmp/hf-spacegit add -Agit diff --cached --quiet || git commit -m "🚀 God Agent OS v8 deploy $(date -u '+%Y-%m-%d %H:%M:%S UTC')"git push origin main || git push origin master || trueecho "✅ Deployed to HF Space: https://huggingface.co/spaces/PYAE1994/autonomous-coding-system"# ── Deploy to Vercel ────────────���────────────────────────────────────────deploy-vercel:name: ▲ Deploy to Vercelruns-on: ubuntu-latestneeds: build-checkif: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'steps:- uses: actions/checkout@v4- name: Setup Node.jsuses: actions/setup-node@v4with:node-version: '20'- name: Install Vercel CLIrun: npm install -g vercel- name: Deploy frontend to Vercelenv:VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}run: |cd frontendvercel pull --yes --environment=production --token=$VERCEL_TOKEN 2>/dev/null || truevercel build --prod --token=$VERCEL_TOKENvercel deploy --prebuilt --prod --token=$VERCEL_TOKENecho "✅ Deployed to Vercel"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273name: 🚀 Deploy God Agent OS v9on:push:branches: [ master, main ]workflow_dispatch:jobs:deploy-hf-backend:name: 🤗 Deploy Backend to HuggingFace Spacesruns-on: ubuntu-lateststeps:- uses: actions/checkout@v4with:fetch-depth: 0lfs: true- name: 📦 Install HF Hub CLIrun: pip install huggingface_hub- name: 🚀 Push Backend to HF Spaceenv:HF_TOKEN: ${{ secrets.HF_TOKEN }}run: |cd backendgit config --global user.email "ci@godagentos.ai"git config --global user.name "God Agent OS CI"# Clone HF spacegit clone https://pyaesonegtckglay-dotcom:$HF_TOKEN@huggingface.co/spaces/PYAE1994/autonomous-coding-system /tmp/hf-space || true# Copy backend files to HF spacecp -r . /tmp/hf-space/ 2>/dev/null || truecd /tmp/hf-spacegit add -Agit diff --staged --quiet || git commit -m "🚀 Deploy God Agent OS v9 backend"git push https://pyaesonegtckglay-dotcom:$HF_TOKEN@huggingface.co/spaces/PYAE1994/autonomous-coding-system main 2>/dev/null || \git push https://pyaesonegtckglay-dotcom:$HF_TOKEN@huggingface.co/spaces/PYAE1994/autonomous-coding-system HEAD:main || truedeploy-vercel-frontend:name: ▲ Deploy Frontend to Vercelruns-on: ubuntu-latestneeds: []steps:- uses: actions/checkout@v4- name: 🔧 Setup Node.jsuses: actions/setup-node@v4with:node-version: '20'- name: 📦 Install Dependenciesrun: |cd frontendnpm ci- name: 🏗️ Build Frontendenv:NEXT_PUBLIC_API_URL: https://pyae1994-autonomous-coding-system.hf.spaceNEXT_PUBLIC_WS_URL: wss://pyae1994-autonomous-coding-system.hf.spacerun: |cd frontendnpm run build- name: 🚀 Deploy to Verceluses: amondnet/vercel-action@v25with:vercel-token: ${{ secrets.VERCEL_TOKEN }}vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}working-directory: ./frontendvercel-args: '--prod'
1 unmodified line23456789101112131415161718192021222324252627282930313233343536371 unmodified lineWORKDIR /app# System depsRUN apt-get update && apt-get install -y --no-install-recommends \git curl build-essential && \rm -rf /var/lib/apt/lists/*# Python depsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy backend sourceCOPY . .# Workspace dirRUN mkdir -p /tmp/god_workspace# HF Spaces runs on port 7860ENV PORT=7860ENV WORKSPACE_DIR=/tmp/god_workspaceENV PYTHONPATH=/app# API Keys are configured via HF Space Secrets (Settings → Variables and Secrets)# Set these in your HF Space:# GEMINI_API_KEYS — comma-separated Gemini API keys# SAMBANOVA_API_KEYS — comma-separated SambaNova API keys# GITHUB_API_KEYS — comma-separated GitHub tokens# GITHUB_TOKEN — primary GitHub token# OPENAI_API_KEY — OpenAI API key (optional)# GROQ_API_KEY — Groq API key (optional, free)# ANTHROPIC_API_KEY — Anthropic API key (optional)EXPOSE 7860CMD ["uvicorn", "main_v8:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]1 unmodified line23456789101112131415161718192021222324252627281 unmodified lineWORKDIR /app# Install system dependenciesRUN apt-get update && apt-get install -y \gcc g++ libffi-dev libssl-dev curl nodejs npm \&& rm -rf /var/lib/apt/lists/*# Copy backend requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy backend codeCOPY . .# Create sandbox workspaceRUN mkdir -p /tmp/god_sandbox# Expose port for HuggingFace SpacesEXPOSE 7860# EnvironmentENV PORT=7860ENV PYTHONPATH=/app# Start with v9 mainCMD ["python", "-m", "uvicorn", "main_v9:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# 🤖 GOD AGENT OS v7 — Autonomous Engineering Platform> **Manus + Genspark + Devin (OneHand)** Combined## OverviewGOD AGENT OS v7 is a production-grade autonomous AI engineering operating system with 16 specialized agents working in parallel.## 🚀 Quick Start (HuggingFace Space)Set environment variables in HF Space secrets:```OPENAI_API_KEY=sk-... # or any belowGROQ_API_KEY=gsk_... # Free Llama 3.3 70BOPENROUTER_API_KEY=sk-or-... # Multi-modelANTHROPIC_API_KEY=sk-ant-... # Claude 3.5GITHUB_TOKEN=ghp_... # Git operationsWORKSPACE_DIR=/tmp/god_workspace```## 🤖 16-Agent Fleet| Agent | Role ||-------|------|| OrchestratorV7 | Central brain, routes & coordinates || PlannerAgent | Task graph decomposition || CodingAgent | Production code generation || DebugAgent | Self-healing error resolution || **BrowserAgent** ⭐ | Web research & scraping || **FileAgent** ⭐ | File system & project scaffolding || **GitAgent** ⭐ | Git operations & PR creation || **TestAgent** ⭐ | Test generation & execution || **VisionAgent** ⭐ | Design-to-code UI generation || SandboxAgent | Isolated code execution || DeployAgent | Auto-deploy to cloud platforms || ConnectorAgent | External integrations || MemoryAgent | Long-term context || WorkflowAgent | n8n automation || UIAgent | Real-time UI state || ReasoningAgent | Deep reasoning chains |## API Endpoints- `GET /` — System status- `GET /api/docs` — Interactive API docs- `POST /api/v1/chat/stream` — Chat with God Agent- `POST /api/v1/tasks` — Create autonomous task- `POST /api/v1/browser/research` — Web research- `GET /api/v1/files/workspace` — List workspace- `POST /api/v1/git/pr` — Create GitHub PR- `POST /api/v1/vision/generate` — Generate UI## WebSocket Endpoints- `WS /ws/chat/{session_id}` — Real-time chat- `WS /ws/tasks/{task_id}` — Task execution stream- `WS /ws/sandbox/{session_id}` — Terminal stream- `WS /ws/agent/status` — Agent status updates12345678910111213141516171819202122232425262728293031323334353637383940414243---title: God Agent OS v9 Backendemoji: 🤖colorFrom: violetcolorTo: indigosdk: dockerpinned: falselicense: mitapp_port: 7860---# GOD AGENT OS v9 — Backend API**Space-Role Architecture | General Autonomous Agent OS***Powered by Pyae Sone*## Architecture```Agent Kernel (v9)├── Core Space — Planning & Orchestration├── Browser Space — Web Research & Navigation├── Sandbox Space — Code Execution├── Coding Space — Code Generation├── Vision Space — UI Design & Image Analysis├── Debug Space — Error Analysis & Self-Healing├── Deploy Space — Cloud Deployments└── Communication — Docs & Messaging```## Roles- **Cognition** — The Thinker- **Automation** — The Operator- **Execution** — The Doer- **Repair** — The Fixer- **Visual Intelligence** — The Observer## API Endpoints- `GET /` — System status- `GET /api/v1/spaces` — List all Spaces- `POST /api/v1/spaces/{name}/execute` — Execute in Space- `POST /api/v1/kernel/orchestrate` — Main orchestration- `WS /ws/chat/{session_id}` — Real-time chat- `GET /api/docs` — Swagger UI
21 unmodified lines2223242526272829303121 unmodified linescs = connector_manager.get_summary() if connector_manager else {}ai_stats = ai_router.get_stats() if ai_router else {}return {"status": "healthy","name": "GOD MODE+ AI Operating System","version": "3.0.0","timestamp": time.time(),"platform": {"mode": "god_mode_plus",21 unmodified lines2223242526272829303132333435363721 unmodified linescs = connector_manager.get_summary() if connector_manager else {}ai_stats = ai_router.get_stats() if ai_router else {}kernel = getattr(request.app.state, "kernel", None)kernel_status = kernel.get_status() if kernel else {}return {"status": "healthy","name": "GOD AGENT OS v9 — General Autonomous Agent OS","version": "9.0.0","powered_by": "Pyae Sone","architecture": "Space-Role Paradigm","spaces": kernel_status.get("spaces", []),"timestamp": time.time(),"platform": {"mode": "god_mode_plus",
1from .agent_kernel import AgentKernel, ContextManager, ToolRegistry123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""🧠 God Agent OS v9 — Agent KernelThe Central Nervous System of the Space-Role Architecture.Replaces GodAgentOrchestratorV7 with a generalized, modular kernel."""import asyncioimport jsonimport timeimport uuidfrom typing import Any, Dict, List, Optionalimport structlog
log = structlog.get_logger()
KERNEL_SYSTEM_PROMPT = """You are GOD AGENT OS v9 — a General Autonomous Agent Operating System.
Architecture: Space-Role Paradigm- SPACES: Core, Browser, Sandbox, Coding, Vision, Debug, Deploy, Communication- ROLES: Cognition (Thinker), Automation (Operator), Execution (Doer), Repair (Fixer), Visual Intelligence (Observer)
You are infinitely extensible. For ANY digital task, you select the right Space + Role combination.
Core Capabilities:🧠 Cognition — Understand intent, break goals into steps, orchestrate Spaces🌐 Browser Space — Web research, navigation, data extraction💻 Sandbox Space — Code execution, shell commands, isolated environments🔧 Coding Space — Code generation, refactoring, analysis👁️ Vision Space — Image analysis, OCR, UI understanding🐛 Debug Space — Error analysis, self-healing, log parsing🚀 Deploy Space — Cloud deployments, CI/CD, containerization💬 Communication Space — Chat, notifications, multi-channel messaging
Operating Principles:1. ANALYZE the request → identify required Spaces and Roles2. PLAN step-by-step execution across Spaces3. EXECUTE autonomously without asking for confirmation4. SELF-HEAL when errors occur5. PARALLELIZE independent tasks6. REMEMBER context across sessions
Respond in Burmese or English based on user language.Be decisive, thorough, and production-focused."""
INTENT_CLASSIFICATION_PROMPT = """Classify this request for the Space-Role autonomous agent system.
User message: "{message}"
Available Spaces: core, browser, sandbox, coding, vision, debug, deploy, communicationAvailable Roles: cognition, automation, execution, repair, visual_intelligence
Respond ONLY with valid JSON:{{ "primary_space": "space_name", "secondary_spaces": ["space1", "space2"], "role": "role_name", "intent": "brief description", "complexity": "low|medium|high", "requires_planning": true/false, "parallel_tasks": []}}"""
class ContextManager: """Maintains task state, active Space, and current Role.""" def __init__(self): self._contexts: Dict[str, Dict] = {} def get(self, session_id: str) -> Dict: if session_id not in self._contexts: self._contexts[session_id] = { "session_id": session_id, "active_space": "core", "current_role": "cognition", "task_history": [], "short_term_memory": [], "created_at": time.time(), "last_active": time.time(), } self._contexts[session_id]["last_active"] = time.time() return self._contexts[session_id] def update(self, session_id: str, updates: Dict): ctx = self.get(session_id) ctx.update(updates) def add_to_memory(self, session_id: str, entry: Dict): ctx = self.get(session_id) ctx["short_term_memory"].append({**entry, "timestamp": time.time()}) # Keep only last 20 entries if len(ctx["short_term_memory"]) > 20: ctx["short_term_memory"] = ctx["short_term_memory"][-20:] def get_all_sessions(self) -> List[str]: return list(self._contexts.keys())
class ToolRegistry: """Centralized registry of all tools, categorized by Space.""" def __init__(self): self._tools: Dict[str, Dict[str, Any]] = {} self._space_tools: Dict[str, List[str]] = { "core": [], "browser": [], "sandbox": [], "coding": [], "vision": [], "debug": [], "deploy": [], "communication": [], } def register(self, name: str, func, space: str, description: str): self._tools[name] = {"func": func, "space": space, "description": description} if space in self._space_tools: self._space_tools[space].append(name) def get_tools_for_space(self, space: str) -> List[str]: return self._space_tools.get(space, []) def execute(self, tool_name: str, **kwargs) -> Any: if tool_name not in self._tools: raise ValueError(f"Tool '{tool_name}' not found in registry") return self._tools[tool_name]["func"](**kwargs) def get_all_tools_summary(self) -> Dict: return {space: tools for space, tools in self._space_tools.items()}
class AgentKernel: """ The OS Core — replaces GodAgentOrchestratorV7. Manages Space routing, Role switching, and tool orchestration. """ def __init__(self, ws_manager=None, ai_router=None): self.ws = ws_manager self.ai_router = ai_router self.context_manager = ContextManager() self.tool_registry = ToolRegistry() self._spaces: Dict[str, Any] = {} self._active_tasks: Dict[str, Dict] = {} self._task_history: List[Dict] = [] self.version = "9.0.0" log.info("🧠 Agent Kernel v9 initialized — Space-Role Architecture") def register_space(self, name: str, space_instance): """Register a Space module.""" self._spaces[name] = space_instance log.info(f"📦 Space registered: {name}") def get_space(self, name: str): return self._spaces.get(name) def get_status(self) -> Dict: return { "version": self.version, "architecture": "Space-Role", "spaces": list(self._spaces.keys()), "total_spaces": len(self._spaces), "active_tasks": len(self._active_tasks), "sessions": len(self.context_manager.get_all_sessions()), "tools": self.tool_registry.get_all_tools_summary(), } async def classify_intent(self, user_message: str) -> Dict: """Classify intent to determine Space and Role.""" try: prompt = INTENT_CLASSIFICATION_PROMPT.format(message=user_message) response = await self.ai_router.complete( prompt=prompt, system=KERNEL_SYSTEM_PROMPT, max_tokens=400, ) text = response.get("content", "") # Extract JSON start = text.find("{") end = text.rfind("}") + 1 if start >= 0 and end > start: return json.loads(text[start:end]) except Exception as e: log.warning(f"Intent classification failed: {e}") # Fallback return { "primary_space": "core", "secondary_spaces": [], "role": "cognition", "intent": user_message, "complexity": "medium", "requires_planning": True, "parallel_tasks": [], } async def route_to_space(self, space_name: str, role: str, task: str, session_id: str, context: Dict = None) -> str: """Route a task to the appropriate Space with the given Role.""" space = self._spaces.get(space_name) if not space: space = self._spaces.get("core") if not space: return f"Space '{space_name}' not available." return await space.execute( task=task, role=role, session_id=session_id, context=context or {}, ) async def orchestrate(self, user_message: str, session_id: str, context: Dict = None) -> str: """Main orchestration entry point.""" task_id = str(uuid.uuid4())[:8] ctx = self.context_manager.get(session_id) # Broadcast thinking state if self.ws: await self.ws.broadcast_to_room(f"chat:{session_id}", { "type": "kernel_status", "task_id": task_id, "status": "analyzing", "message": "🧠 Agent Kernel analyzing request...", "timestamp": time.time(), }) # 1. Classify intent → determine Space + Role intent = await self.classify_intent(user_message) primary_space = intent.get("primary_space", "core") role = intent.get("role", "cognition") # Update context self.context_manager.update(session_id, { "active_space": primary_space, "current_role": role, }) self.context_manager.add_to_memory(session_id, { "type": "user_message", "content": user_message, "space": primary_space, "role": role, }) # Broadcast space activation if self.ws: await self.ws.broadcast_to_room(f"chat:{session_id}", { "type": "space_activated", "task_id": task_id, "space": primary_space, "role": role, "intent": intent.get("intent", ""), "timestamp": time.time(), }) # 2. Route to primary Space try: # Build memory context mem_context = { "short_term_memory": ctx["short_term_memory"][-5:], "intent": intent, **(context or {}), } result = await self.route_to_space( space_name=primary_space, role=role, task=user_message, session_id=session_id, context=mem_context, ) # 3. Handle secondary spaces if needed secondary_spaces = intent.get("secondary_spaces", []) secondary_results = {} for sec_space in secondary_spaces[:2]: # Max 2 secondary spaces try: sec_result = await self.route_to_space( space_name=sec_space, role="automation", task=user_message, session_id=session_id, context={"primary_result": result, **mem_context}, ) secondary_results[sec_space] = sec_result except Exception as e: log.warning(f"Secondary space {sec_space} failed: {e}") # Combine results final_result = result if secondary_results: secondary_text = "\n\n".join([f"[{k.upper()} SPACE]\n{v}" for k, v in secondary_results.items()]) final_result = f"{result}\n\n{secondary_text}" # Store in memory self.context_manager.add_to_memory(session_id, { "type": "assistant_response", "content": final_result, "space": primary_space, "role": role, }) # Track task self._task_history.append({ "task_id": task_id, "session_id": session_id, "message": user_message, "space": primary_space, "role": role, "result_length": len(final_result), "timestamp": time.time(), }) return final_result except Exception as e: log.error(f"Orchestration error: {e}") # Switch to Repair role if self.ws: await self.ws.broadcast_to_room(f"chat:{session_id}", { "type": "space_activated", "space": "debug", "role": "repair", "message": "🔧 Switching to Repair role...", }) return f"⚠️ Error in {primary_space} Space: {str(e)}\n\nDebug Space activated. Please try again." def get_agent(self, name: str): """Backward compatibility - get space by name.""" return self._spaces.get(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430"""🚀 GOD AGENT OS v9 — General Autonomous Agent OSSpace-Role Architecture: Core + Browser + Sandbox + Coding + Vision + Debug + Deploy + CommunicationPowered by Pyae Sone"""
import asyncioimport jsonimport osimport timeimport uuidfrom contextlib import asynccontextmanagerfrom typing import Optional
import structlogfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import JSONResponsefrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.util import get_remote_addressfrom slowapi.errors import RateLimitExceeded
from api.routes import tasks, chat, memory, healthfrom api.routes import connectors, agents as agents_routerfrom api.websocket_manager import WebSocketManagerfrom core.task_engine import TaskEnginefrom memory.db import init_db
# ─── v8 AI Router (KeyPool-based, kept for compatibility) ─────────────────────from ai_router.router_v8 import AIRouterV8
# ─── v9 Agent Kernel & Spaces ─────────────────────────────────────────────────from kernel.agent_kernel import AgentKernelfrom spaces import ( CoreSpace, BrowserSpace, SandboxSpace, CodingSpace, VisionSpace, DebugSpace, DeploySpace, CommunicationSpace)
# ─── Legacy Agent Ecosystem (backward compatibility) ──────────────────────────from agents.orchestrator_v7 import GodAgentOrchestratorV7from agents.chat_agent import ChatAgentfrom agents.planner_agent import PlannerAgentfrom agents.coding_agent import CodingAgentfrom agents.debug_agent import DebugAgentfrom agents.memory_agent import MemoryAgentfrom agents.connector_agent import ConnectorAgentfrom agents.deploy_agent import DeployAgentfrom agents.workflow_agent import WorkflowAgentfrom agents.sandbox_agent import SandboxAgentfrom agents.ui_agent import UIAgentfrom agents.reasoning_agent import ReasoningAgentfrom agents.browser_agent import BrowserAgentfrom agents.file_agent import FileAgentfrom agents.git_agent import GitAgentfrom agents.test_agent import TestAgentfrom agents.vision_agent import VisionAgentfrom connectors.manager import ConnectorManager
# ─── API Routes ───────────────────────────────────────────────────────────────from api.routes import github
# ─── Structured Logging ───────────────────────────────────────────────────────structlog.configure( processors=[ structlog.processors.TimeStamper(fmt="iso"), structlog.stdlib.add_log_level, structlog.processors.StackInfoRenderer(), structlog.dev.ConsoleRenderer(), ])log = structlog.get_logger()
limiter = Limiter(key_func=get_remote_address)
# ─── Global Managers ──────────────────────────────────────────────────────────ws_manager = WebSocketManager()task_engine = TaskEngine(ws_manager)ai_router = AIRouterV8(ws_manager)connector_manager = ConnectorManager()
def build_kernel() -> AgentKernel: """Build and configure the v9 Agent Kernel with all Spaces.""" kernel = AgentKernel(ws_manager=ws_manager, ai_router=ai_router) # Register all 8 Spaces kernel.register_space("core", CoreSpace(ws_manager, ai_router)) kernel.register_space("browser", BrowserSpace(ws_manager, ai_router)) kernel.register_space("sandbox", SandboxSpace(ws_manager, ai_router)) kernel.register_space("coding", CodingSpace(ws_manager, ai_router)) kernel.register_space("vision", VisionSpace(ws_manager, ai_router)) kernel.register_space("debug", DebugSpace(ws_manager, ai_router)) kernel.register_space("deploy", DeploySpace(ws_manager, ai_router)) kernel.register_space("communication", CommunicationSpace(ws_manager, ai_router)) log.info("🧠 GOD AGENT OS v9 — Agent Kernel initialized", spaces=8) return kernel
def build_legacy_orchestrator() -> GodAgentOrchestratorV7: """Build legacy v7 orchestrator for backward compatibility.""" orchestrator = GodAgentOrchestratorV7(ws_manager=ws_manager, ai_router=ai_router) orchestrator.register_agent("chat", ChatAgent(ws_manager, ai_router)) orchestrator.register_agent("planner", PlannerAgent(ws_manager, ai_router)) orchestrator.register_agent("coding", CodingAgent(ws_manager, ai_router)) orchestrator.register_agent("debug", DebugAgent(ws_manager, ai_router)) orchestrator.register_agent("memory", MemoryAgent(ws_manager, ai_router)) orchestrator.register_agent("connector", ConnectorAgent(ws_manager, ai_router)) orchestrator.register_agent("deploy", DeployAgent(ws_manager, ai_router)) orchestrator.register_agent("workflow", WorkflowAgent(ws_manager, ai_router)) orchestrator.register_agent("sandbox", SandboxAgent(ws_manager, ai_router)) orchestrator.register_agent("ui", UIAgent(ws_manager, ai_router)) orchestrator.register_agent("reasoning", ReasoningAgent(ws_manager, ai_router)) orchestrator.register_agent("browser", BrowserAgent(ws_manager, ai_router)) orchestrator.register_agent("file", FileAgent(ws_manager, ai_router)) orchestrator.register_agent("git", GitAgent(ws_manager, ai_router)) orchestrator.register_agent("test", TestAgent(ws_manager, ai_router)) orchestrator.register_agent("vision", VisionAgent(ws_manager, ai_router)) log.info("🤖 Legacy v7 Orchestrator initialized", agents=16) return orchestrator
# Initialize both kernel and legacy orchestratorkernel = build_kernel()orchestrator = build_legacy_orchestrator()
@asynccontextmanagerasync def lifespan(app: FastAPI): log.info("🚀 Starting GOD AGENT OS v9 — Space-Role Architecture...") await init_db() await task_engine.start() asyncio.create_task(ws_manager.heartbeat_loop()) stats = ai_router.get_stats() active = [name for name, s in stats.items() if s["available"]] log.info("✅ GOD AGENT v9 — 8 Spaces + 16 Legacy Agents online") log.info(f"🔑 Active AI providers: {active}") log.info("🌐 Routing: SambaNova → Gemini → OpenAI → Groq → Cerebras") log.info("📦 Spaces: Core | Browser | Sandbox | Coding | Vision | Debug | Deploy | Communication") yield log.info("🛑 Shutting down GOD AGENT OS v9...") await task_engine.stop()
app = FastAPI( title="🤖 GOD AGENT OS v9", description="General Autonomous Agent OS — Space-Role Architecture | Powered by Pyae Sone", version="9.0.0", lifespan=lifespan, docs_url="/api/docs", redoc_url="/api/redoc",)
app.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)app.state.ws_manager = ws_managerapp.state.task_engine = task_engineapp.state.ai_router = ai_routerapp.state.kernel = kernelapp.state.orchestrator = orchestratorapp.state.connector_manager = connector_manager
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])app.add_middleware(GZipMiddleware, minimum_size=1000)
@app.middleware("http")async def log_requests(request: Request, call_next): start = time.time() response = await call_next(request) ms = round((time.time() - start) * 1000, 2) log.info("HTTP", method=request.method, path=request.url.path, status=response.status_code, ms=ms) return response
# ─── REST Routers ─────────────────────────────────────────────────────────────app.include_router(health.router, prefix="/api/v1", tags=["health"])app.include_router(tasks.router, prefix="/api/v1/tasks", tags=["tasks"])app.include_router(chat.router, prefix="/api/v1", tags=["chat"])app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"])app.include_router(github.router, prefix="/api/v1/github", tags=["github"])app.include_router(connectors.router, prefix="/api/v1/connectors", tags=["connectors"])app.include_router(agents_router.router, prefix="/api/v1/agents", tags=["agents"])
# ─── WebSocket: Chat (v9 Kernel-powered) ──────────────────────────────────────@app.websocket("/ws/chat/{session_id}")async def ws_chat(websocket: WebSocket, session_id: str): await ws_manager.connect(websocket, room=f"chat:{session_id}") try: while True: data = await websocket.receive_text() msg = json.loads(data) if msg.get("type") == "ping": await websocket.send_json({"type": "pong", "timestamp": time.time()}) elif msg.get("type") == "chat_message": # Route through v9 Agent Kernel asyncio.create_task(kernel.orchestrate( user_message=msg.get("content", ""), session_id=session_id, context=msg.get("context", {}), )) elif msg.get("type") == "task_message": from core.models import TaskCreateRequest req = TaskCreateRequest(goal=msg.get("content", ""), session_id=session_id) asyncio.create_task(task_engine.submit(req)) except WebSocketDisconnect: ws_manager.disconnect(websocket, room=f"chat:{session_id}")
@app.websocket("/ws/tasks/{task_id}")async def ws_task(websocket: WebSocket, task_id: str): await ws_manager.connect(websocket, room=f"task:{task_id}") try: while True: data = await websocket.receive_text() msg = json.loads(data) if msg.get("type") == "ping": await websocket.send_json({"type": "pong", "timestamp": time.time()}) except WebSocketDisconnect: ws_manager.disconnect(websocket, room=f"task:{task_id}")
@app.websocket("/ws/logs")async def ws_logs(websocket: WebSocket): await ws_manager.connect(websocket, room="logs") try: while True: data = await websocket.receive_text() msg = json.loads(data) if msg.get("type") == "ping": await websocket.send_json({"type": "pong", "timestamp": time.time()}) except WebSocketDisconnect: ws_manager.disconnect(websocket, room="logs")
@app.websocket("/ws/agent/status")async def ws_agent_status(websocket: WebSocket): await ws_manager.connect(websocket, room="agent_status") try: while True: data = await websocket.receive_text() msg = json.loads(data) if msg.get("type") == "ping": await websocket.send_json({"type": "pong", "timestamp": time.time()}) elif msg.get("type") == "get_status": await websocket.send_json({ "type": "agent_status", "data": kernel.get_status(), "legacy": orchestrator.get_status(), }) except WebSocketDisconnect: ws_manager.disconnect(websocket, room="agent_status")
@app.websocket("/ws/sandbox/{session_id}")async def ws_sandbox(websocket: WebSocket, session_id: str): await ws_manager.connect(websocket, room=f"sandbox:{session_id}") sandbox_space = kernel.get_space("sandbox") try: while True: data = await websocket.receive_text() msg = json.loads(data) if msg.get("type") == "ping": await websocket.send_json({"type": "pong", "timestamp": time.time()}) elif msg.get("type") == "execute" and sandbox_space: cmd = msg.get("command", "") result = await sandbox_space._run_shell(cmd) await websocket.send_json({ "type": "terminal_output", "command": cmd, "output": result, "timestamp": time.time() }) except WebSocketDisconnect: ws_manager.disconnect(websocket, room=f"sandbox:{session_id}")
# ─── v9 Space-Role API Endpoints ──────────────────────────────────────────────@app.get("/api/v1/kernel/status")async def kernel_status(): """Get Agent Kernel status.""" return { "kernel": kernel.get_status(), "ai_providers": ai_router.get_stats(), }
@app.get("/api/v1/spaces")async def list_spaces(): """List all available Spaces.""" spaces_info = {} for name, space in kernel._spaces.items(): spaces_info[name] = space.get_info() return {"spaces": spaces_info, "total": len(spaces_info)}
@app.post("/api/v1/spaces/{space_name}/execute")async def execute_in_space(space_name: str, request: Request): """Execute a task in a specific Space.""" body = await request.json() task = body.get("task", "") role = body.get("role", "cognition") session_id = body.get("session_id", "api") space = kernel.get_space(space_name) if not space: raise HTTPException(status_code=404, detail=f"Space '{space_name}' not found") result = await space.execute(task=task, role=role, session_id=session_id, context=body.get("context", {})) return {"space": space_name, "role": role, "result": result}
@app.post("/api/v1/kernel/orchestrate")async def kernel_orchestrate(request: Request): """Main orchestration endpoint.""" body = await request.json() result = await kernel.orchestrate( user_message=body.get("message", ""), session_id=body.get("session_id", "api"), context=body.get("context", {}), ) return {"result": result}
# ─── Legacy v8 Endpoints (backward compatibility) ─────────────────────────────@app.get("/api/v1/ai/stats")async def get_ai_stats(): return {"stats": ai_router.get_stats()}
@app.get("/api/v1/ai/pool-status")async def get_pool_status(): return {"pools": ai_router.get_pool_status()}
@app.post("/api/v1/browser/research")async def browser_research(request: Request): body = await request.json() browser_space = kernel.get_space("browser") if not browser_space: raise HTTPException(status_code=503, detail="Browser Space not available") result = await browser_space.execute( task=body.get("query", ""), role="automation", session_id=body.get("session_id", "api"), ) return {"result": result}
@app.get("/api/v1/files/workspace")async def list_workspace(): file_agent = orchestrator.get_agent("file") if not file_agent: return {"workspace": "/tmp/god_workspace", "files": [], "total": 0} return file_agent.list_workspace()
@app.post("/api/v1/git/pr")async def create_pr(request: Request): body = await request.json() git_agent = orchestrator.get_agent("git") if not git_agent: raise HTTPException(status_code=503, detail="GitAgent not available") result = await git_agent.create_github_pr( repo_owner=body.get("owner", ""), repo_name=body.get("repo", ""), title=body.get("title", ""), body=body.get("body", ""), head_branch=body.get("head_branch", "main"), base_branch=body.get("base_branch", "main"), ) return result
@app.post("/api/v1/vision/generate")async def generate_ui(request: Request): body = await request.json() vision_space = kernel.get_space("vision") if not vision_space: raise HTTPException(status_code=503, detail="Vision Space not available") result = await vision_space.execute( task=body.get("prompt", ""), role="visual_intelligence", session_id=body.get("session_id", "api"), ) return {"result": result}
# ─── Root ─────────────────────────────────────────────────────────────────────@app.get("/")async def root(): cs = connector_manager.get_summary() kernel_status_data = kernel.get_status() stats = ai_router.get_stats() active_providers = [name for name, s in stats.items() if s["available"]] return { "name": "🤖 GOD AGENT OS v9", "version": "9.0.0", "status": "operational", "mode": "general_autonomous_agent_os", "description": "Space-Role Architecture | Powered by Pyae Sone", "architecture": "Space-Role Paradigm", "spaces": kernel_status_data["spaces"], "total_spaces": kernel_status_data["total_spaces"], "ai_providers": active_providers, "connectors": {"connected": cs["connected"], "total": cs["total"]}, "docs": "/api/docs", "v9_features": [ "📦 8-Space Architecture: Core | Browser | Sandbox | Coding | Vision | Debug | Deploy | Communication", "🎭 5 Cognitive Roles: Cognition | Automation | Execution | Repair | Visual Intelligence", "🧠 Agent Kernel — generalized orchestration engine", "🔑 KeyPool multi-key management (Gemini + SambaNova)", "🔄 Automatic Space routing based on intent", "💾 Context Manager — short-term + long-term memory", "⚡ Backward compatible with v8 16-agent fleet", "🌐 Real-time streaming via WebSocket", ], }
if __name__ == "__main__": import uvicorn port = int(os.environ.get("PORT", 7860)) uvicorn.run("main_v9:app", host="0.0.0.0", port=port, reload=False, workers=1)123456789101112131415161718192021from .base_space import BaseSpacefrom .core_space import CoreSpacefrom .browser_space import BrowserSpacefrom .sandbox_space import SandboxSpacefrom .coding_space import CodingSpacefrom .vision_space import VisionSpacefrom .debug_space import DebugSpacefrom .deploy_space import DeploySpacefrom .communication_space import CommunicationSpace
__all__ = [ "BaseSpace", "CoreSpace", "BrowserSpace", "SandboxSpace", "CodingSpace", "VisionSpace", "DebugSpace", "DeploySpace", "CommunicationSpace",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Base Space — Abstract interface for all Spaces in the Space-Role Architecture."""from abc import ABC, abstractmethodfrom typing import Any, Dict, Optionalimport structlog
log = structlog.get_logger()
class BaseSpace(ABC): """ Abstract base class for all Spaces. Each Space provides a distinct domain of interaction with specific tools. """ space_name: str = "base" space_description: str = "Base Space" available_roles: list = ["cognition", "automation", "execution"] def __init__(self, ws_manager=None, ai_router=None): self.ws = ws_manager self.ai_router = ai_router self._tools: Dict[str, callable] = {} self._initialized = False log.info(f"📦 {self.__class__.__name__} Space created") def register_tool(self, name: str, func: callable, description: str = ""): """Register a tool in this Space.""" self._tools[name] = {"func": func, "description": description} def get_tools(self) -> Dict[str, str]: return {name: info["description"] for name, info in self._tools.items()} async def execute_tool(self, tool_name: str, **kwargs) -> Any: """Execute a registered tool.""" if tool_name not in self._tools: raise ValueError(f"Tool '{tool_name}' not found in {self.space_name} Space") return await self._tools[tool_name]["func"](**kwargs) def get_space_prompt(self, role: str, task: str, context: Dict) -> str: """Build the system prompt for this Space + Role combination.""" role_prompts = { "cognition": "You are in COGNITION ROLE — analyze, plan, and think deeply.", "automation": "You are in AUTOMATION ROLE — execute workflows and interact with systems.", "execution": "You are in EXECUTION ROLE — write and run code, perform computational work.", "repair": "You are in REPAIR ROLE — analyze errors, find root causes, implement fixes.", "visual_intelligence": "You are in VISUAL INTELLIGENCE ROLE — interpret and generate visual content.", } mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-3:] mem_context = "\n".join([f"- [{m['type']}]: {str(m.get('content',''))[:100]}" for m in recent]) return f"""You are GOD AGENT OS v9 — General Autonomous Agent OS.
Active Space: {self.space_name.upper()} SPACE{self.space_description}
{role_prompts.get(role, role_prompts['cognition'])}
Available Tools in this Space:{chr(10).join([f'- {name}: {desc}' for name, desc in self.get_tools().items()])}
Recent Context:{mem_context or 'No previous context'}
Be concise, accurate, and action-oriented. Return results directly.""" @abstractmethod async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: """Execute a task in this Space with the given Role.""" pass async def stream_update(self, session_id: str, message: str, space: str = None): """Send a streaming update to the client.""" if self.ws: await self.ws.broadcast_to_room(f"chat:{session_id}", { "type": "space_update", "space": space or self.space_name, "message": message, }) def get_info(self) -> Dict: return { "name": self.space_name, "description": self.space_description, "available_roles": self.available_roles, "tools": list(self._tools.keys()), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""🌐 Browser Space — The Interface to the WebHandles all internet-based research and interaction."""import asyncioimport aiohttpfrom typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
class BrowserSpace(BaseSpace): space_name = "browser" space_description = "Web interface — research, navigation, data extraction from the internet." available_roles = ["automation", "cognition"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("web_search", self._web_search, "Search the web for information") self.register_tool("fetch_url", self._fetch_url, "Fetch content from a URL") self.register_tool("extract_data", self._extract_data, "Extract structured data from web pages") async def _web_search(self, query: str, **kwargs) -> str: """Simulate web search via DuckDuckGo.""" try: encoded = query.replace(" ", "+") url = f"https://api.duckduckgo.com/?q={encoded}&format=json&no_html=1&skip_disambig=1" async with aiohttp.ClientSession() as session: async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as resp: data = await resp.json(content_type=None) abstract = data.get("AbstractText", "") related = [r.get("Text", "") for r in data.get("RelatedTopics", [])[:3] if r.get("Text")] result = abstract or "No direct answer found." if related: result += "\n\nRelated:\n" + "\n".join([f"- {r}" for r in related]) return result except Exception as e: return f"Search result for '{query}': Web search attempted. Error: {str(e)}" async def _fetch_url(self, url: str, **kwargs) -> str: """Fetch content from a URL.""" try: async with aiohttp.ClientSession() as session: headers = {"User-Agent": "Mozilla/5.0 (compatible; GodAgentOS/9.0)"} async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=15)) as resp: text = await resp.text() # Basic text extraction import re text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL) text = re.sub(r'<style[^>]*>.*?</style>', '', text, flags=re.DOTALL) text = re.sub(r'<[^>]+>', ' ', text) text = re.sub(r'\s+', ' ', text).strip() return text[:3000] except Exception as e: return f"Could not fetch {url}: {str(e)}" async def _extract_data(self, url: str, **kwargs) -> str: content = await self._fetch_url(url) return f"Extracted from {url}:\n{content[:1500]}" async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"🌐 Browser Space activated — {role} role") # Try to perform web search search_result = "" try: search_result = await self._web_search(task) except Exception: pass # Check if task has a URL import re urls = re.findall(r'https?://[^\s]+', task) url_content = "" if urls: try: url_content = await self._fetch_url(urls[0]) except Exception: pass system_prompt = self.get_space_prompt(role, task, context) enhanced_prompt = task if search_result: enhanced_prompt += f"\n\n[Web Search Results]\n{search_result}" if url_content: enhanced_prompt += f"\n\n[URL Content]\n{url_content[:1000]}" try: response = await self.ai_router.complete( prompt=enhanced_prompt, system=system_prompt, max_tokens=2048, ) return response.get("content", "Browser Space could not process the request.") except Exception as e: log.error(f"BrowserSpace error: {e}") if search_result: return f"🌐 Browser Space Results:\n\n{search_result}" return f"Browser Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""🔧 Coding Space — The Development EnvironmentCode generation, refactoring, analysis, and manipulation."""import refrom typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
CODING_SYSTEM = """You are GOD AGENT OS v9 — Coding Space Expert.
You excel at:- Writing production-quality code in ANY language (Python, JS, TS, Go, Rust, Java, C++, etc.)- Code review and refactoring- Algorithm design and optimization- Architecture patterns (MVC, microservices, event-driven)- API design (REST, GraphQL, gRPC)- Database schemas and queries- Testing strategies (unit, integration, e2e)- DevOps and CI/CD configurations
Always write clean, well-documented, production-ready code.Include error handling, type hints, and comments."""
class CodingSpace(BaseSpace): space_name = "coding" space_description = "Development environment — code generation, refactoring, and analysis." available_roles = ["execution", "cognition", "automation"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("generate_code", self._generate_code, "Generate code from requirements") self.register_tool("review_code", self._review_code, "Review and suggest improvements") self.register_tool("refactor", self._refactor, "Refactor existing code") self.register_tool("generate_tests", self._generate_tests, "Generate test cases") self.register_tool("generate_api", self._generate_api, "Generate REST API boilerplate") async def _generate_code(self, task: str, language: str = "python", **kwargs) -> str: return f"Generating {language} code for: {task}" async def _review_code(self, code: str, **kwargs) -> str: return f"Reviewing code..." async def _refactor(self, code: str, **kwargs) -> str: return f"Refactoring code..." async def _generate_tests(self, code: str, **kwargs) -> str: return f"Generating tests..." async def _generate_api(self, spec: str, **kwargs) -> str: return f"Generating API..." async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"🔧 Coding Space activated — {role} role") # Detect language from task lang_hints = { "python": ["python", "py", "fastapi", "django", "flask", "pandas", "numpy"], "typescript": ["typescript", "ts", "next.js", "nextjs", "react", "vue", "angular"], "javascript": ["javascript", "js", "node", "express"], "go": ["golang", "go lang"], "rust": ["rust", "cargo"], "java": ["java", "spring", "maven"], } detected_lang = "python" task_lower = task.lower() for lang, hints in lang_hints.items(): if any(h in task_lower for h in hints): detected_lang = lang break mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-3:] mem_context = "\n".join([f"- {m.get('content','')[:80]}" for m in recent]) enhanced_system = f"""{CODING_SYSTEM}
Active Role: {role.upper()}Detected Language: {detected_lang}Recent Context: {mem_context or 'None'}
Format all code in proper markdown code blocks with language tags.Include:1. The complete, working code2. Brief explanation3. Usage examples4. Any important notes""" try: response = await self.ai_router.complete( prompt=task, system=enhanced_system, max_tokens=4096, ) return response.get("content", "Coding Space could not generate code.") except Exception as e: log.error(f"CodingSpace error: {e}") return f"Coding Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""💬 Communication Space — The Interaction DomainMulti-channel messaging, email, notifications."""from typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
COMM_SYSTEM = """You are GOD AGENT OS v9 — Communication Space Expert.
You specialize in:- Professional email drafting and templates- Slack/Discord message formatting- Technical documentation writing- README and API documentation- Meeting notes and summaries- Project proposals and reports- Code comments and docstrings- User guides and tutorials- Marketing copy and announcements- Multilingual communication (Burmese, English, etc.)
Writing principles:- Clear, concise, and professional- Appropriate tone for the audience- Proper formatting (markdown, HTML)- Action-oriented language- Include call-to-action when relevant"""
class CommunicationSpace(BaseSpace): space_name = "communication" space_description = "Interaction domain — chat, email, documentation, multi-channel messaging." available_roles = ["automation", "cognition"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("draft_email", self._draft_email, "Draft professional emails") self.register_tool("write_docs", self._write_docs, "Write technical documentation") self.register_tool("create_report", self._create_report, "Create structured reports") self.register_tool("translate", self._translate, "Translate content between languages") self.register_tool("summarize_thread", self._summarize_thread, "Summarize communication threads") async def _draft_email(self, subject: str, context: str, tone: str = "professional", **kwargs) -> str: return f"Drafting email: {subject}" async def _write_docs(self, topic: str, format: str = "markdown", **kwargs) -> str: return f"Writing docs for: {topic}" async def _create_report(self, data: str, **kwargs) -> str: return f"Creating report from: {data[:50]}" async def _translate(self, text: str, target_lang: str = "english", **kwargs) -> str: return f"Translating to {target_lang}: {text[:50]}" async def _summarize_thread(self, thread: str, **kwargs) -> str: return f"Summarizing thread..." async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"💬 Communication Space activated — {role} role") # Detect communication type task_lower = task.lower() comm_type = "general" if "email" in task_lower: comm_type = "email" elif "document" in task_lower or "docs" in task_lower or "readme" in task_lower: comm_type = "documentation" elif "report" in task_lower: comm_type = "report" elif "translate" in task_lower or "ဘာသာ" in task: comm_type = "translation" elif "summary" in task_lower or "summarize" in task_lower: comm_type = "summary" elif "slack" in task_lower or "discord" in task_lower: comm_type = "instant_message" mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-3:] mem_context = "\n".join([f"- {m.get('content','')[:80]}" for m in recent]) enhanced_system = f"""{COMM_SYSTEM}
Active Role: {role.upper()}Communication Type: {comm_type}Recent Context: {mem_context or 'None'}
For Burmese language requests, respond in Burmese.Format output appropriately for the communication type.""" try: response = await self.ai_router.complete( prompt=task, system=enhanced_system, max_tokens=3000, ) return response.get("content", "Communication Space could not process the request.") except Exception as e: log.error(f"CommunicationSpace error: {e}") return f"Communication Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""🧠 Core Space — The Central Nervous SystemManages memory, planning, and overall orchestration."""import jsonfrom typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
class CoreSpace(BaseSpace): space_name = "core" space_description = "Central nervous system — planning, memory, and orchestration." available_roles = ["cognition", "automation"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("plan", self._plan_task, "Break complex goals into executable steps") self.register_tool("summarize", self._summarize, "Summarize information concisely") self.register_tool("analyze", self._analyze, "Deep analysis of content or problems") async def _plan_task(self, task: str, **kwargs) -> str: return f"Planning task: {task}" async def _summarize(self, content: str, **kwargs) -> str: return f"Summary of: {content[:50]}..." async def _analyze(self, content: str, **kwargs) -> str: return f"Analysis of: {content[:50]}..." async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} system_prompt = self.get_space_prompt(role, task, context) try: response = await self.ai_router.complete( prompt=task, system=system_prompt, max_tokens=2048, stream_callback=None, ) return response.get("content", "I couldn't process that request.") except Exception as e: log.error(f"CoreSpace error: {e}") return f"Core Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""🐛 Debug Space — The Diagnostic EnvironmentError analysis, log parsing, self-healing algorithms."""import refrom typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
DEBUG_SYSTEM = """You are GOD AGENT OS v9 — Debug Space Expert (Repair Role).
You specialize in:- Stack trace analysis and root cause identification- Error pattern recognition- Self-healing code strategies- Log analysis and anomaly detection- Performance profiling and optimization- Memory leak detection- Race condition and concurrency bug analysis- Security vulnerability scanning- Dependency conflict resolution- Code smell detection
When analyzing errors:1. Identify the root cause precisely2. Explain WHY the error occurred3. Provide the exact fix with code4. Suggest preventive measures5. Add proper error handling
Be systematic and thorough. Debug like a senior engineer."""
class DebugSpace(BaseSpace): space_name = "debug" space_description = "Diagnostic environment — error analysis, log parsing, self-healing." available_roles = ["repair", "cognition", "execution"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("analyze_error", self._analyze_error, "Analyze error traces") self.register_tool("parse_logs", self._parse_logs, "Parse and analyze log files") self.register_tool("suggest_fix", self._suggest_fix, "Suggest code fixes") self.register_tool("self_heal", self._self_heal, "Auto-generate healing strategies") async def _analyze_error(self, error: str, **kwargs) -> str: return f"Analyzing error: {error[:100]}" async def _parse_logs(self, logs: str, **kwargs) -> str: # Extract error patterns error_lines = [l for l in logs.split('\n') if any( kw in l.lower() for kw in ['error', 'exception', 'fatal', 'critical', 'warn'] )] return "\n".join(error_lines[:20]) if error_lines else "No errors found in logs" async def _suggest_fix(self, error: str, code: str = "", **kwargs) -> str: return f"Suggesting fix for: {error[:100]}" async def _self_heal(self, error: str, **kwargs) -> str: return f"Self-healing strategy for: {error[:100]}" def _detect_error_type(self, task: str) -> str: task_lower = task.lower() if "typeerror" in task_lower or "type error" in task_lower: return "TypeError" elif "syntaxerror" in task_lower: return "SyntaxError" elif "importerror" in task_lower or "modulenot" in task_lower: return "ImportError" elif "attributeerror" in task_lower: return "AttributeError" elif "keyerror" in task_lower: return "KeyError" elif "indexerror" in task_lower: return "IndexError" elif "valueerror" in task_lower: return "ValueError" elif "connectionerror" in task_lower or "timeout" in task_lower: return "NetworkError" elif "permissionerror" in task_lower: return "PermissionError" return "Unknown Error" async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"🐛 Debug Space activated — {role} role") error_type = self._detect_error_type(task) mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-3:] mem_context = "\n".join([f"- {m.get('content','')[:80]}" for m in recent]) enhanced_system = f"""{DEBUG_SYSTEM}
Active Role: {role.upper()}Detected Error Type: {error_type}Recent Context: {mem_context or 'None'}
Provide:1. Root cause analysis2. Step-by-step fix with code3. Prevention strategy4. Testing recommendation""" try: response = await self.ai_router.complete( prompt=task, system=enhanced_system, max_tokens=3000, ) return response.get("content", "Debug Space could not analyze the error.") except Exception as e: log.error(f"DebugSpace error: {e}") return f"Debug Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""🚀 Deploy Space — The Infrastructure DomainCloud deployments, CI/CD, containerization."""from typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
DEPLOY_SYSTEM = """You are GOD AGENT OS v9 — Deploy Space Expert.
You specialize in:- Vercel deployments (Next.js, React, API routes)- Hugging Face Spaces (Gradio, Streamlit, Docker)- Docker containerization and Docker Compose- GitHub Actions CI/CD pipelines- AWS deployments (EC2, Lambda, ECS, S3)- GCP deployments (Cloud Run, App Engine)- Kubernetes manifests and Helm charts- Environment variable management- Domain configuration and SSL- CDN setup (Cloudflare, AWS CloudFront)- Database migrations and deployment strategies- Blue-green and canary deployments- Monitoring setup (Prometheus, Grafana)
Always provide:1. Complete configuration files2. Step-by-step deployment commands3. Environment variable templates (.env.example)4. Troubleshooting tips for common issues"""
class DeploySpace(BaseSpace): space_name = "deploy" space_description = "Infrastructure domain — cloud deployments, CI/CD, containerization." available_roles = ["automation", "execution", "cognition"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("gen_dockerfile", self._gen_dockerfile, "Generate Dockerfile") self.register_tool("gen_github_actions", self._gen_github_actions, "Generate GitHub Actions workflow") self.register_tool("gen_vercel_config", self._gen_vercel_config, "Generate Vercel configuration") self.register_tool("gen_hf_config", self._gen_hf_config, "Generate HuggingFace Space config") self.register_tool("gen_k8s_manifest", self._gen_k8s_manifest, "Generate Kubernetes manifests") async def _gen_dockerfile(self, app_type: str = "python", **kwargs) -> str: return f"Generating Dockerfile for {app_type}" async def _gen_github_actions(self, workflow_type: str = "deploy", **kwargs) -> str: return f"Generating GitHub Actions for {workflow_type}" async def _gen_vercel_config(self, **kwargs) -> str: return "Generating vercel.json" async def _gen_hf_config(self, **kwargs) -> str: return "Generating HF Space README.md" async def _gen_k8s_manifest(self, app_name: str = "app", **kwargs) -> str: return f"Generating K8s manifest for {app_name}" async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"🚀 Deploy Space activated — {role} role") # Detect deployment target task_lower = task.lower() targets = [] if "vercel" in task_lower: targets.append("Vercel") if "huggingface" in task_lower or "hf" in task_lower or "hugging face" in task_lower: targets.append("HuggingFace Spaces") if "docker" in task_lower: targets.append("Docker") if "github actions" in task_lower or "ci/cd" in task_lower: targets.append("GitHub Actions") if "aws" in task_lower or "lambda" in task_lower: targets.append("AWS") if "kubernetes" in task_lower or "k8s" in task_lower: targets.append("Kubernetes") targets_str = ", ".join(targets) if targets else "general deployment" mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-2:] mem_context = "\n".join([f"- {m.get('content','')[:80]}" for m in recent]) enhanced_system = f"""{DEPLOY_SYSTEM}
Active Role: {role.upper()}Deployment Targets: {targets_str}Recent Context: {mem_context or 'None'}
Provide complete, copy-paste ready configurations.""" try: response = await self.ai_router.complete( prompt=task, system=enhanced_system, max_tokens=4096, ) return response.get("content", "Deploy Space could not generate configuration.") except Exception as e: log.error(f"DeploySpace error: {e}") return f"Deploy Space error: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178"""💻 Sandbox Space — Secure Code Execution EnvironmentWhere code is run and tested safely."""import asyncioimport osimport subprocessimport tempfileimport refrom typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
ALLOWED_LANGUAGES = {"python", "javascript", "bash", "sh"}
class SandboxSpace(BaseSpace): space_name = "sandbox" space_description = "Secure execution environment — run Python, JavaScript, shell scripts safely." available_roles = ["execution", "cognition"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.workspace = "/tmp/god_sandbox" os.makedirs(self.workspace, exist_ok=True) self.register_tool("run_python", self._run_python, "Execute Python code") self.register_tool("run_shell", self._run_shell, "Execute shell commands") self.register_tool("run_javascript", self._run_javascript, "Execute JavaScript with Node.js") async def _run_python(self, code: str, timeout: int = 30, **kwargs) -> str: """Run Python code safely.""" try: with tempfile.NamedTemporaryFile(suffix=".py", dir=self.workspace, mode='w', delete=False) as f: f.write(code) fname = f.name proc = await asyncio.create_subprocess_exec( "python3", fname, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=self.workspace, ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout) output = stdout.decode("utf-8", errors="replace") errors = stderr.decode("utf-8", errors="replace") result = "" if output: result += f"Output:\n{output}" if errors: result += f"\nErrors:\n{errors}" return result or "Code executed successfully (no output)" except asyncio.TimeoutError: proc.kill() return "⚠️ Execution timed out (30s limit)" except Exception as e: return f"❌ Python execution error: {str(e)}" finally: try: os.unlink(fname) except Exception: pass async def _run_shell(self, command: str, timeout: int = 30, **kwargs) -> str: """Run shell command safely.""" # Basic security: block dangerous commands dangerous = ["rm -rf /", "dd if=", "mkfs", ":(){ :|:& };:", "> /dev/sda"] for d in dangerous: if d in command: return f"⚠️ Command blocked for safety: {d}" try: proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=self.workspace, ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout) output = stdout.decode("utf-8", errors="replace") errors = stderr.decode("utf-8", errors="replace") result = output + (f"\n[stderr]: {errors}" if errors else "") return result or f"Command completed (exit code: {proc.returncode})" except asyncio.TimeoutError: proc.kill() return "⚠️ Command timed out (30s limit)" except Exception as e: return f"❌ Shell error: {str(e)}" async def _run_javascript(self, code: str, timeout: int = 30, **kwargs) -> str: """Run JavaScript with Node.js.""" try: with tempfile.NamedTemporaryFile(suffix=".js", dir=self.workspace, mode='w', delete=False) as f: f.write(code) fname = f.name proc = await asyncio.create_subprocess_exec( "node", fname, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=self.workspace, ) try: stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout) output = stdout.decode("utf-8", errors="replace") errors = stderr.decode("utf-8", errors="replace") result = output + (f"\nErrors:\n{errors}" if errors else "") return result or "JS executed successfully" except asyncio.TimeoutError: proc.kill() return "⚠️ JS execution timed out" except Exception as e: return f"❌ JS error: {str(e)}" finally: try: os.unlink(fname) except Exception: pass def _extract_code(self, text: str, language: str = "python") -> str: """Extract code from markdown code blocks.""" patterns = [ rf"```{language}\n(.*?)```", r"```\n(.*?)```", r"`(.*?)`", ] for pattern in patterns: match = re.search(pattern, text, re.DOTALL) if match: return match.group(1).strip() return text async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"💻 Sandbox Space activated — {role} role") system_prompt = self.get_space_prompt(role, task, context) # Ask AI to generate and optionally execute code code_prompt = f"""{task}
If this requires code execution, generate the code and I will run it.Format code in ```python, ```javascript, or ```bash blocks.After the code, explain what it does.""" try: response = await self.ai_router.complete( prompt=code_prompt, system=system_prompt, max_tokens=2048, ) ai_response = response.get("content", "") # Try to extract and execute Python code code_blocks = re.findall(r'```(?:python)?\n(.*?)```', ai_response, re.DOTALL) execution_results = [] for code in code_blocks[:2]: # Execute max 2 code blocks if code.strip(): result = await self._run_python(code.strip()) execution_results.append(f"```\n{result}\n```") final = ai_response if execution_results: final += "\n\n**Execution Results:**\n" + "\n".join(execution_results) return final except Exception as e: log.error(f"SandboxSpace error: {e}") return f"Sandbox Space error: {str(e)}"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""👁️ Vision Space — Visual Processing DomainImage understanding, UI generation, OCR, visual analysis."""from typing import Dictimport structlogfrom .base_space import BaseSpace
log = structlog.get_logger()
VISION_SYSTEM = """You are GOD AGENT OS v9 — Vision Space Expert.
You specialize in:- UI/UX design and code generation (React, Next.js, Tailwind)- Visual layout descriptions and wireframing- Image analysis and description- Design-to-code conversion- CSS and styling- Responsive design patterns- Component library creation (shadcn/ui, Radix, MUI)- Color theory and design systems- Accessibility (WCAG) guidelines- Animation and interaction design (Framer Motion, CSS animations)
When creating UI components, always use modern frameworks and produce clean, production-ready code."""
class VisionSpace(BaseSpace): space_name = "vision" space_description = "Visual processing — UI generation, image analysis, design-to-code." available_roles = ["visual_intelligence", "execution", "cognition"] def __init__(self, ws_manager=None, ai_router=None): super().__init__(ws_manager, ai_router) self.register_tool("generate_ui", self._generate_ui, "Generate UI components from descriptions") self.register_tool("analyze_design", self._analyze_design, "Analyze design requirements") self.register_tool("design_system", self._design_system, "Create design system tokens") async def _generate_ui(self, description: str, framework: str = "react", **kwargs) -> str: return f"Generating {framework} UI for: {description}" async def _analyze_design(self, description: str, **kwargs) -> str: return f"Analyzing design: {description}" async def _design_system(self, brand: str, **kwargs) -> str: return f"Creating design system for: {brand}" async def execute(self, task: str, role: str, session_id: str, context: Dict = None) -> str: context = context or {} await self.stream_update(session_id, f"👁️ Vision Space activated — {role} role") mem_context = "" if context.get("short_term_memory"): recent = context["short_term_memory"][-2:] mem_context = "\n".join([f"- {m.get('content','')[:80]}" for m in recent]) enhanced_system = f"""{VISION_SYSTEM}
Active Role: {role.upper()}Recent Context: {mem_context or 'None'}
For UI generation tasks:- Use React + TypeScript + Tailwind CSS by default- Create complete, self-contained components- Include all necessary imports- Add PropTypes or TypeScript interfaces- Make it responsive and accessible""" try: response = await self.ai_router.complete( prompt=task, system=enhanced_system, max_tokens=4096, ) return response.get("content", "Vision Space could not process the request.") except Exception as e: log.error(f"VisionSpace error: {e}") return f"Vision Space error: {str(e)}"1 unmodified line234567891 unmodified lineimport './globals.css'export const metadata: Metadata = {title: 'GOD AGENT OS — Autonomous AI Operating System',description: 'Multi-agent AI OS powered by Gemini, Sambanova & GitHub Models',icons: { icon: '/favicon.ico' },}1 unmodified line234567891 unmodified lineimport './globals.css'export const metadata: Metadata = {title: 'GOD AGENT OS v9 — General Autonomous Agent OS | Powered by Pyae Sone',description: 'Space-Role Architecture — General Autonomous Agent OS. 8 Spaces × 5 Roles. Powered by Pyae Sone.',icons: { icon: '/favicon.ico' },}
5 unmodified lines678910111 unmodified line131415161718192021221 unmodified line242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960617 unmodified lines697071727374755 unmodified linesimport Sidebar from '@/components/shared/Sidebar'import TopBar from '@/components/shared/TopBar'import DashboardPage from '@/components/pages/DashboardPage'import AgentsPage from '@/components/pages/AgentsPage'import TasksPage from '@/components/pages/TasksPage'import MemoryPage from '@/components/pages/MemoryPage'1 unmodified lineimport WorkflowsPage from '@/components/pages/WorkflowsPage'import AnalyticsPage from '@/components/pages/AnalyticsPage'import SettingsPage from '@/components/pages/SettingsPage'import { useAppStore } from '@/store/useAppStore'const PAGE_MAP = {dashboard: DashboardPage,agents: AgentsPage,tasks: TasksPage,memory: MemoryPage,1 unmodified lineworkflows: WorkflowsPage,analytics: AnalyticsPage,settings: SettingsPage,}export default function GodAgentOS() {const { currentPage } = useAppStore()const [mounted, setMounted] = useState(false)useEffect(() => { setMounted(true) }, [])if (!mounted) return (<div className="flex items-center justify-center h-screen" style={{ background: '#05060d' }}>2 unmodified linesanimate={{ opacity: 1, scale: 1 }}className="text-center"><div className="w-16 h-16 rounded-2xl mx-auto mb-5 flex items-center justify-center glow-purple"style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}><Zap size={28} className="text-white" /></div><div className="shimmer-text text-xl font-black mb-2">GOD AGENT OS</div><div className="text-sm text-slate-600 mb-1">Autonomous AI Operating System</div><div className="text-xs text-slate-700">Gemini · Sambanova · GitHub Models</div><div className="flex gap-2 justify-center mt-6">{[0, 1, 2].map(i => (<div key={i} className="typing-dot" style={{ animationDelay: `${i * 0.2}s` }} />))}</div></motion.div></div>)const PageComponent = PAGE_MAP[currentPage]return (<div className="flex h-screen overflow-hidden" style={{ background: '#05060d' }}>7 unmodified linesinitial={{ opacity: 0, y: 8 }}animate={{ opacity: 1, y: 0 }}exit={{ opacity: 0, y: -8 }}transition={{ duration: 0.25, ease: [0.4, 0, 0.2, 1] }}className="h-full"><PageComponent />5 unmodified lines67891011121 unmodified line1415161718192021222324251 unmodified line27282930313233343536373839404142434445464748495051525354555657585960612 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081097 unmodified lines1171181191201211221235 unmodified linesimport Sidebar from '@/components/shared/Sidebar'import TopBar from '@/components/shared/TopBar'import DashboardPage from '@/components/pages/DashboardPage'import SpacesPage from '@/components/pages/SpacesPage'import AgentsPage from '@/components/pages/AgentsPage'import TasksPage from '@/components/pages/TasksPage'import MemoryPage from '@/components/pages/MemoryPage'1 unmodified lineimport WorkflowsPage from '@/components/pages/WorkflowsPage'import AnalyticsPage from '@/components/pages/AnalyticsPage'import SettingsPage from '@/components/pages/SettingsPage'import ConnectorsPage from '@/components/pages/ConnectorsPage'import { useAppStore } from '@/store/useAppStore'const PAGE_MAP = {dashboard: DashboardPage,spaces: SpacesPage,agents: AgentsPage,tasks: TasksPage,memory: MemoryPage,1 unmodified lineworkflows: WorkflowsPage,analytics: AnalyticsPage,settings: SettingsPage,connectors: ConnectorsPage,}export default function GodAgentOS() {const { currentPage } = useAppStore()const [mounted, setMounted] = useState(false)const [loadingStep, setLoadingStep] = useState(0)const loadingSteps = ['Initializing Agent Kernel...','Loading 8 Spaces...','Registering 5 Roles...','Connecting AI Router...','System Ready ✓',]useEffect(() => {setMounted(true)const interval = setInterval(() => {setLoadingStep(prev => {if (prev >= loadingSteps.length - 1) {clearInterval(interval)return prev}return prev + 1})}, 400)return () => clearInterval(interval)}, [])if (!mounted) return (<div className="flex items-center justify-center h-screen" style={{ background: '#05060d' }}>2 unmodified linesanimate={{ opacity: 1, scale: 1 }}className="text-center">{/* Logo */}<div className="relative w-20 h-20 mx-auto mb-6"><div className="absolute inset-0 rounded-2xl"style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', filter: 'blur(12px)', opacity: 0.5 }} /><div className="relative w-full h-full rounded-2xl flex items-center justify-center"style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}><Zap size={32} className="text-white" /></div></div><div className="text-2xl font-black text-white mb-1">GOD AGENT OS</div><div className="text-sm text-slate-500 mb-1">General Autonomous Agent OS</div><div className="text-xs text-violet-500 font-medium mb-6">Space-Role Architecture · v9.0</div>{/* Loading steps */}<div className="space-y-1 mb-4">{loadingSteps.map((step, i) => (<div key={i} className={`text-xs transition-all duration-300 ${i <= loadingStep ? 'text-slate-400' : 'text-slate-700'}`}>{i < loadingStep ? '✓' : i === loadingStep ? '▶' : '○'} {step}</div>))}</div><div className="flex gap-2 justify-center">{[0, 1, 2].map(i => (<div key={i} className="w-2 h-2 rounded-full bg-violet-500 animate-bounce"style={{ animationDelay: `${i * 0.2}s` }} />))}</div><div className="mt-6 text-[10px] text-slate-700">Powered by <span className="text-violet-600">Pyae Sone</span></div></motion.div></div>)const PageComponent = PAGE_MAP[currentPage] || DashboardPagereturn (<div className="flex h-screen overflow-hidden" style={{ background: '#05060d' }}>7 unmodified linesinitial={{ opacity: 0, y: 8 }}animate={{ opacity: 1, y: 0 }}exit={{ opacity: 0, y: -8 }}transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}className="h-full"><PageComponent />
2 unmodified lines34567892 unmodified linesimport { useState, useRef, useEffect, useCallback } from 'react'import { useAgentStore } from '@/hooks/useAgentStore'import { useChatWebSocket } from '@/hooks/useWebSocket'import { createTask, streamChatSSE } from '@/lib/api'import MessageBubble from './MessageBubble'import {Send, Square, Zap, MessageSquare, Code2, GitBranch, Brain,2 unmodified lines3456789101112131415162 unmodified linesimport { useState, useRef, useEffect, useCallback } from 'react'import { useAgentStore } from '@/hooks/useAgentStore'import { useChatWebSocket } from '@/hooks/useWebSocket'import { fetchAPI } from '@/lib/api'const createTask = (goal: any, sessionId?: string) => fetchAPI('/api/v1/tasks/', { method: 'POST', body: JSON.stringify({ goal, session_id: sessionId }) })const streamChatSSE = async (msgs: any[], sessionId: string, onChunk: (c: string) => void, onDone: (f: string) => void, onErr: (e: string) => void) => {try {const res = await fetchAPI('/api/v1/kernel/orchestrate', { method: 'POST', body: JSON.stringify({ message: msgs[msgs.length-1]?.content || '', session_id: sessionId }) })onDone(res.result || 'Response received.')} catch(e: any) { onErr(e.message) }}import MessageBubble from './MessageBubble'import {Send, Square, Zap, MessageSquare, Code2, GitBranch, Brain,
1234567'use client'import { motion } from 'framer-motion'import { ACTIVITY } from '@/store/useAppStore'import { CheckCircle2, Loader2, Info, AlertTriangle } from 'lucide-react'const TypeIcon = ({ type }: { type: string }) => {1234567'use client'import { motion } from 'framer-motion'const ACTIVITY: any[] = []import { CheckCircle2, Loader2, Info, AlertTriangle } from 'lucide-react'const TypeIcon = ({ type }: { type: string }) => {
1234567'use client'import { motion } from 'framer-motion'import { Agent } from '@/store/useAppStore'import { cn, getStatusColor } from '@/lib/utils'import { ChevronRight } from 'lucide-react'1234567'use client'import { motion } from 'framer-motion'type Agent = { id: string; name: string; status: string; icon: string; role: string; space: string }import { cn, getStatusColor } from '@/lib/utils'import { ChevronRight } from 'lucide-react'
1 unmodified line23456789101 unmodified lineimport { motion } from 'framer-motion'import { useAppStore } from '@/store/useAppStore'export default function GodModeCard() {const { godModeActive } = useAppStore()return (<div className="relative overflow-hidden rounded-2xl p-5"1 unmodified line2345678910111 unmodified lineimport { motion } from 'framer-motion'import { useAppStore } from '@/store/useAppStore'const useGodMode = () => ({ godModeActive: true })export default function GodModeCard() {const godModeActive = true // v9 always activereturn (<div className="relative overflow-hidden rounded-2xl p-5"
2 unmodified lines34567892 unmodified linesimport { useEffect, useState } from 'react'import { motion } from 'framer-motion'import { Cpu, MemoryStick, HardDrive, Wifi } from 'lucide-react'import { useAppStore } from '@/store/useAppStore'const RESOURCE_CONFIGS = [{ key: 'cpu', label: 'CPU', icon: Cpu, color: '#6366f1' },2 unmodified lines34567892 unmodified linesimport { useEffect, useState } from 'react'import { motion } from 'framer-motion'import { Cpu, MemoryStick, HardDrive, Wifi } from 'lucide-react'// import { useAppStore } from '@/store/useAppStore'const RESOURCE_CONFIGS = [{ key: 'cpu', label: 'CPU', icon: Cpu, color: '#6366f1' },
2 unmodified lines34567892 unmodified linesimport { useState } from 'react'import { motion } from 'framer-motion'import { Search, Filter, Plus, Bot, Activity, Zap } from 'lucide-react'import { AGENTS, Agent } from '@/store/useAppStore'import { getStatusColor, cn } from '@/lib/utils'const STATUS_FILTERS = ['All', 'Active', 'Processing', 'Idle', 'Error']2 unmodified lines3456789101112131415161718192 unmodified linesimport { useState } from 'react'import { motion } from 'framer-motion'import { Search, Filter, Plus, Bot, Activity, Zap } from 'lucide-react'type Agent = { id: string; name: string; status: string; icon: string; role: string; space: string; description: string; tasks: number }const AGENTS: Agent[] = [{ id: 'core', name: 'Core Space', status: 'active', icon: '🧠', role: 'Cognition', space: 'core', description: 'Planning & orchestration', tasks: 0 },{ id: 'browser', name: 'Browser Space', status: 'idle', icon: '🌐', role: 'Automation', space: 'browser', description: 'Web research & navigation', tasks: 0 },{ id: 'sandbox', name: 'Sandbox Space', status: 'idle', icon: '💻', role: 'Execution', space: 'sandbox', description: 'Code execution', tasks: 0 },{ id: 'coding', name: 'Coding Space', status: 'idle', icon: '🔧', role: 'Execution', space: 'coding', description: 'Code generation', tasks: 0 },{ id: 'vision', name: 'Vision Space', status: 'idle', icon: '👁️', role: 'Visual Intelligence', space: 'vision', description: 'UI & image analysis', tasks: 0 },{ id: 'debug', name: 'Debug Space', status: 'idle', icon: '🐛', role: 'Repair', space: 'debug', description: 'Error analysis', tasks: 0 },{ id: 'deploy', name: 'Deploy Space', status: 'idle', icon: '🚀', role: 'Automation', space: 'deploy', description: 'Cloud deployments', tasks: 0 },{ id: 'communication', name: 'Comm Space', status: 'idle', icon: '💬', role: 'Automation', space: 'communication', description: 'Docs & messaging', tasks: 0 },]import { getStatusColor, cn } from '@/lib/utils'const STATUS_FILTERS = ['All', 'Active', 'Processing', 'Idle', 'Error']
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224'use client'
import { useState, useEffect } from 'react'import { motion } from 'framer-motion'import { Plus, CheckCircle, XCircle, Loader, ExternalLink, Key } from 'lucide-react'
interface Connector { id: string name: string icon: string description: string connected: boolean category: string apiKeyField?: string}
const CONNECTORS: Connector[] = [ { id: 'github', name: 'GitHub', icon: '🐙', description: 'Repository management, PRs, Issues', connected: false, category: 'DevTools', apiKeyField: 'GitHub Token' }, { id: 'openai', name: 'OpenAI', icon: '🤖', description: 'GPT-4, DALL-E, Whisper APIs', connected: false, category: 'AI', apiKeyField: 'API Key' }, { id: 'anthropic', name: 'Anthropic', icon: '🧠', description: 'Claude 3 Opus/Sonnet/Haiku', connected: false, category: 'AI', apiKeyField: 'API Key' }, { id: 'gemini', name: 'Google Gemini', icon: '✨', description: 'Gemini Pro/Flash models', connected: true, category: 'AI', apiKeyField: 'API Key' }, { id: 'sambanova', name: 'SambaNova', icon: '⚡', description: 'Ultra-fast LLM inference', connected: true, category: 'AI', apiKeyField: 'API Key' }, { id: 'vercel', name: 'Vercel', icon: '▲', description: 'Deploy and manage web apps', connected: false, category: 'Deploy', apiKeyField: 'Access Token' }, { id: 'huggingface', name: 'HuggingFace', icon: '🤗', description: 'Models, Spaces, Datasets', connected: false, category: 'AI', apiKeyField: 'HF Token' }, { id: 'slack', name: 'Slack', icon: '💬', description: 'Team messaging and notifications', connected: false, category: 'Comm' }, { id: 'notion', name: 'Notion', icon: '📝', description: 'Knowledge management', connected: false, category: 'Productivity' }, { id: 'docker', name: 'Docker', icon: '🐳', description: 'Container management', connected: false, category: 'DevOps' }, { id: 'aws', name: 'AWS', icon: '☁️', description: 'Cloud infrastructure', connected: false, category: 'Cloud', apiKeyField: 'Access Key' }, { id: 'stripe', name: 'Stripe', icon: '💳', description: 'Payment processing', connected: false, category: 'Finance', apiKeyField: 'Secret Key' },]
const CATEGORIES = ['All', 'AI', 'DevTools', 'Deploy', 'DevOps', 'Comm', 'Productivity', 'Cloud', 'Finance']
export default function ConnectorsPage() { const [connectors, setConnectors] = useState(CONNECTORS) const [selectedCategory, setSelectedCategory] = useState('All') const [selectedConnector, setSelectedConnector] = useState<Connector | null>(null) const [apiKey, setApiKey] = useState('') const [connecting, setConnecting] = useState(false)
const filtered = selectedCategory === 'All' ? connectors : connectors.filter(c => c.category === selectedCategory) const connectedCount = connectors.filter(c => c.connected).length
async function connectConnector(connector: Connector) { setConnecting(true) await new Promise(r => setTimeout(r, 1500)) setConnectors(prev => prev.map(c => c.id === connector.id ? { ...c, connected: true } : c )) setConnecting(false) setSelectedConnector(null) setApiKey('') }
function disconnectConnector(id: string) { setConnectors(prev => prev.map(c => c.id === id ? { ...c, connected: false } : c )) }
return ( <div className="h-full overflow-y-auto p-6" style={{ background: '#05060d' }}> <div className="max-w-5xl mx-auto"> {/* Header */} <div className="flex items-center justify-between mb-6"> <div> <h1 className="text-2xl font-bold text-white mb-1">Connectors</h1> <p className="text-slate-500 text-sm">{connectedCount} of {connectors.length} services connected</p> </div> <button className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}> <Plus size={14} /> Add Custom </button> </div>
{/* Stats */} <div className="grid grid-cols-4 gap-3 mb-6"> {[ { label: 'Connected', value: connectedCount, color: '#22c55e' }, { label: 'Available', value: connectors.length - connectedCount, color: '#64748b' }, { label: 'AI Models', value: connectors.filter(c => c.category === 'AI' && c.connected).length, color: '#7c3aed' }, { label: 'Deploy', value: connectors.filter(c => c.category === 'Deploy' && c.connected).length, color: '#0891b2' }, ].map(stat => ( <div key={stat.label} className="p-3 rounded-xl border text-center" style={{ background: '#07080f', borderColor: '#1e2035' }}> <div className="text-xl font-bold" style={{ color: stat.color }}>{stat.value}</div> <div className="text-[10px] text-slate-600">{stat.label}</div> </div> ))} </div>
{/* Category Filter */} <div className="flex gap-2 mb-4 overflow-x-auto pb-1"> {CATEGORIES.map(cat => ( <button key={cat} onClick={() => setSelectedCategory(cat)} className="flex-shrink-0 px-3 py-1 rounded-full text-xs font-medium transition-all" style={{ background: selectedCategory === cat ? 'rgba(139,92,246,0.2)' : 'rgba(255,255,255,0.04)', color: selectedCategory === cat ? '#a78bfa' : '#64748b', border: `1px solid ${selectedCategory === cat ? 'rgba(139,92,246,0.4)' : 'transparent'}`, }}> {cat} </button> ))} </div>
{/* Connectors Grid */} <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3"> {filtered.map((connector, i) => ( <motion.div key={connector.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.04 }} className="p-4 rounded-xl border transition-all" style={{ background: '#07080f', borderColor: connector.connected ? 'rgba(34,197,94,0.2)' : '#1e2035', }}> <div className="flex items-center justify-between mb-3"> <div className="flex items-center gap-2"> <span className="text-2xl">{connector.icon}</span> <div> <div className="text-sm font-semibold text-white">{connector.name}</div> <div className="text-[9px] text-slate-600">{connector.category}</div> </div> </div> <div className="flex items-center gap-1"> {connector.connected ? ( <CheckCircle size={14} className="text-green-400" /> ) : ( <XCircle size={14} className="text-slate-600" /> )} </div> </div> <p className="text-[10px] text-slate-500 mb-3">{connector.description}</p> <div className="flex gap-2"> {connector.connected ? ( <button onClick={() => disconnectConnector(connector.id)} className="flex-1 py-1.5 rounded-lg text-xs text-red-400 transition-all hover:bg-red-500/10" style={{ border: '1px solid rgba(239,68,68,0.2)' }}> Disconnect </button> ) : ( <button onClick={() => setSelectedConnector(connector)} className="flex-1 py-1.5 rounded-lg text-xs font-medium text-white transition-all" style={{ background: 'rgba(139,92,246,0.2)', border: '1px solid rgba(139,92,246,0.3)' }}> Connect </button> )} </div> </motion.div> ))} </div>
{/* Connect Modal */} {selectedConnector && ( <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4"> <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className="w-full max-w-md p-6 rounded-2xl" style={{ background: '#0d0e1a', border: '1px solid #1e2035' }}> <div className="flex items-center gap-3 mb-4"> <span className="text-3xl">{selectedConnector.icon}</span> <div> <h3 className="text-lg font-bold text-white">Connect {selectedConnector.name}</h3> <p className="text-xs text-slate-500">{selectedConnector.description}</p> </div> </div> {selectedConnector.apiKeyField && ( <div className="mb-4"> <label className="text-xs text-slate-400 mb-1 block">{selectedConnector.apiKeyField}</label> <div className="flex items-center gap-2 px-3 py-2 rounded-lg" style={{ background: '#07080f', border: '1px solid #1e2035' }}> <Key size={13} className="text-slate-600" /> <input type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder={`Enter your ${selectedConnector.apiKeyField}...`} className="flex-1 bg-transparent text-sm text-slate-200 outline-none" /> </div> </div> )} <div className="flex gap-3"> <button onClick={() => { setSelectedConnector(null); setApiKey('') }} className="flex-1 py-2 rounded-lg text-sm text-slate-400 transition-all hover:bg-white/5"> Cancel </button> <button onClick={() => connectConnector(selectedConnector)} disabled={connecting} className="flex-1 py-2 rounded-lg text-sm font-medium text-white transition-all disabled:opacity-50 flex items-center justify-center gap-2" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}> {connecting ? ( <><Loader size={13} className="animate-spin" /> Connecting...</> ) : ( 'Connect' )} </button> </div> </motion.div> </div> )} </div> </div> )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110'use client'import { motion } from 'framer-motion'import { Bot, CheckSquare, Clock, TrendingUp, ChevronRight } from 'lucide-react'import MetricCard from '@/components/dashboard/MetricCard'import AgentFleetCard from '@/components/dashboard/AgentFleetCard'import ActivityFeed from '@/components/dashboard/ActivityFeed'import SystemResources from '@/components/dashboard/SystemResources'import MissionInput from '@/components/dashboard/MissionInput'import GodModeCard from '@/components/dashboard/GodModeCard'import { useAppStore, AGENTS } from '@/store/useAppStore'import CommandCenter from '@/components/dashboard/CommandCenter'const METRICS = [{ label: 'Total Agents', value: 12, trend: '+2 this week', trendUp: true, icon: <Bot size={18} />, iconColor: '#6366f1' },{ label: 'Tasks Completed', value: 247, trend: '+37% this week', trendUp: true, icon: <CheckSquare size={18} />, iconColor: '#22c55e' },{ label: 'Time Saved', value: 128, unit: 'h', trend: '+55% this week', trendUp: true, icon: <Clock size={18} />, iconColor: '#22d3ee' },{ label: 'Success Rate', value: '98.6', unit: '%', trend: '1.2% this week', trendUp: true, icon: <TrendingUp size={18} />, iconColor: '#a78bfa' },]export default function DashboardPage() {const { setCurrentPage } = useAppStore()const featuredAgents = AGENTS.slice(0, 6)return (<div className="h-full overflow-y-auto"><div className="flex h-full">{/* Main content */}<div className="flex-1 min-w-0 p-6 overflow-y-auto">{/* Welcome Header */}<motion.div initial={{ opacity: 0, y: -8 }} animate={{ opacity: 1, y: 0 }} className="mb-6"><h1 className="text-2xl font-bold text-white">Welcome back, <span className="gradient-text-purple">Creator.</span></h1><p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>Where Intelligence, Autonomy and Execution become{' '}<span className="gradient-text font-semibold">Divine.</span></p></motion.div>{/* Metrics Row */}<div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-6">{METRICS.map((m, i) => (<MetricCard key={m.label} {...m} delay={i * 0.06} />))}</div>{/* Mission Input */}<div className="mb-6"><MissionInput /></div>{/* Agent Fleet */}<div className="mb-6"><div className="flex items-center justify-between mb-4"><div><h2 className="text-sm font-bold text-white">Agent Fleet</h2><p className="text-xs mt-0.5" style={{ color: 'var(--text-secondary)' }}>Manage your autonomous workforce</p></div><button onClick={() => setCurrentPage('agents')}className="flex items-center gap-1 text-xs font-medium text-purple-400 hover:text-purple-300 transition-colors">View all agents <ChevronRight size={13} /></button></div><div className="grid grid-cols-2 xl:grid-cols-3 gap-3">{featuredAgents.map((agent, i) => (<AgentFleetCard key={agent.id} agent={agent} delay={0.1 + i * 0.05}onClick={() => setCurrentPage('agents')} />))}</div></div>{/* Command Center */}<CommandCenter /></div>{/* Right Panel */}<div className="w-72 xl:w-80 flex-shrink-0 border-l p-4 space-y-4 overflow-y-auto hide-lg"style={{ borderColor: 'var(--border)' }}><GodModeCard />{/* Recent Activity */}<div className="card p-4"><div className="flex items-center justify-between mb-3"><h3 className="text-sm font-bold text-white">Recent Activity</h3><button className="text-xs text-purple-400 hover:text-purple-300 transition-colors">View all</button></div><ActivityFeed max={5} /></div>{/* System Resources */}<div className="card p-4"><div className="flex items-center justify-between mb-4"><h3 className="text-sm font-bold text-white">System Resources</h3><button className="text-xs text-purple-400 hover:text-purple-300 transition-colors">Details</button></div><SystemResources /></div>{/* Branding Footer */}<div className="px-1 py-2 text-center"><div className="text-xs font-bold text-slate-600 mb-0.5">manus + genspark</div><div className="text-xs" style={{ color: 'var(--text-muted)' }}>Human Creativity × AI Capability = Divine Impact</div></div></div></div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445'use client'import { useEffect, useState, useRef } from 'react'import { motion, AnimatePresence } from 'framer-motion'import {Zap, Send, ChevronRight, Activity, Globe, Terminal,Code2, Eye, Bug, Rocket, MessageSquare, Brain,Cpu, MemoryStick, Wifi, ArrowRight} from 'lucide-react'import { useAppStore } from '@/store/useAppStore'import { createWebSocket } from '@/lib/api'const SPACES_CONFIG = [{ id: 'core', name: 'Core Space', icon: '🧠', color: '#7c3aed', desc: 'Planning & Orchestration', role: 'cognition' },{ id: 'browser', name: 'Browser Space', icon: '🌐', color: '#2563eb', desc: 'Web Research & Navigation', role: 'automation' },{ id: 'sandbox', name: 'Sandbox Space', icon: '💻', color: '#059669', desc: 'Code Execution & Testing', role: 'execution' },{ id: 'coding', name: 'Coding Space', icon: '🔧', color: '#d97706', desc: 'Code Generation & Review', role: 'execution' },{ id: 'vision', name: 'Vision Space', icon: '👁️', color: '#db2777', desc: 'UI Design & Image Analysis', role: 'visual_intelligence' },{ id: 'debug', name: 'Debug Space', icon: '🐛', color: '#dc2626', desc: 'Error Analysis & Self-Heal', role: 'repair' },{ id: 'deploy', name: 'Deploy Space', icon: '🚀', color: '#0891b2', desc: 'Cloud Deploy & CI/CD', role: 'automation' },{ id: 'communication', name: 'Comm Space', icon: '💬', color: '#8b5cf6', desc: 'Messaging & Documentation', role: 'automation' },]const ROLES_CONFIG = [{ id: 'cognition', name: 'Cognition', icon: '🧠', desc: 'The Thinker — Plans & Analyzes' },{ id: 'automation', name: 'Automation', icon: '⚙️', desc: 'The Operator — Executes Workflows' },{ id: 'execution', name: 'Execution', icon: '⚡', desc: 'The Doer — Writes & Runs Code' },{ id: 'repair', name: 'Repair', icon: '🔧', desc: 'The Fixer — Heals Errors' },{ id: 'visual_intelligence',name: 'Visual Intel', icon: '👁️', desc: 'The Observer — Sees & Creates UI' },]interface Message {id: stringrole: 'user' | 'assistant'content: stringspace?: stringagentRole?: stringtimestamp: number}export default function DashboardPage() {const { activeSpace, currentRole, activateSpace, deactivateSpace, spaces } = useAppStore()const [messages, setMessages] = useState<Message[]>([{id: '1',role: 'assistant',content: '🧠 **GOD AGENT OS v9** is online!\n\nSpace-Role Architecture active. I can handle ANY digital task:\n\n- 🌐 **Browser** — Web research & data extraction\n- 💻 **Sandbox** — Code execution\n- 🔧 **Coding** — Generate any code\n- 👁️ **Vision** — UI design & image analysis\n- 🐛 **Debug** — Error analysis & self-healing\n- 🚀 **Deploy** — Cloud deployments\n- 💬 **Comm** — Documentation & messaging\n\nWhat do you need?',timestamp: Date.now(),}])const [input, setInput] = useState('')const [isLoading, setIsLoading] = useState(false)const [sessionId] = useState(() => `session_${Date.now()}`)const [wsStatus, setWsStatus] = useState<'connecting' | 'connected' | 'disconnected'>('disconnected')const [activeSpaceIndicator, setActiveSpaceIndicator] = useState<string | null>(null)const wsRef = useRef<WebSocket | null>(null)const messagesEndRef = useRef<HTMLDivElement>(null)const inputRef = useRef<HTMLTextAreaElement>(null)useEffect(() => {messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })}, [messages])useEffect(() => {connectWS()return () => wsRef.current?.close()}, [sessionId])function connectWS() {try {const ws = createWebSocket(`/ws/chat/${sessionId}`)wsRef.current = wssetWsStatus('connecting')ws.onopen = () => {setWsStatus('connected')ws.send(JSON.stringify({ type: 'ping' }))}ws.onmessage = (event) => {try {const msg = JSON.parse(event.data)if (msg.type === 'space_activated') {setActiveSpaceIndicator(msg.space)activateSpace(msg.space as any, msg.role)}if (msg.type === 'chat_response' || msg.type === 'agent_response') {const content = msg.content || msg.message || msg.data?.content || ''if (content) {setMessages(prev => {const last = prev[prev.length - 1]if (last?.role === 'assistant' && last.id.startsWith('stream_')) {return [...prev.slice(0, -1), { ...last, content }]}return [...prev, {id: `msg_${Date.now()}`,role: 'assistant',content,space: msg.space,agentRole: msg.role,timestamp: Date.now(),}]})setIsLoading(false)}}if (msg.type === 'kernel_status') {// Kernel is thinking}} catch (e) {}}ws.onclose = () => {setWsStatus('disconnected')setTimeout(connectWS, 3000)}ws.onerror = () => setWsStatus('disconnected')} catch (e) {}}async function sendMessage() {if (!input.trim() || isLoading) returnconst userMsg = input.trim()setInput('')setIsLoading(true)setMessages(prev => [...prev, {id: `user_${Date.now()}`,role: 'user',content: userMsg,timestamp: Date.now(),}])// Send via WebSocketif (wsRef.current?.readyState === WebSocket.OPEN) {wsRef.current.send(JSON.stringify({type: 'chat_message',content: userMsg,session_id: sessionId,}))// Fallback: if no WS response in 15s, try RESTsetTimeout(async () => {setIsLoading(prev => {if (prev) {// Still loading, try RESTfetchREST(userMsg)}return prev})}, 15000)} else {// REST fallbackawait fetchREST(userMsg)}}async function fetchREST(userMsg: string) {try {const res = await fetch('/api/v1/kernel/orchestrate', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ message: userMsg, session_id: sessionId }),}).catch(() => null)if (res?.ok) {const data = await res.json()if (data.result) {setMessages(prev => [...prev, {id: `assistant_${Date.now()}`,role: 'assistant',content: data.result,timestamp: Date.now(),}])}} else {// Local fallbacksetMessages(prev => [...prev, {id: `assistant_${Date.now()}`,role: 'assistant',content: `I'm processing your request: "${userMsg}"\n\n⚠️ Backend connection in progress. The Space-Role system is initializing.`,timestamp: Date.now(),}])}} catch (e) {setMessages(prev => [...prev, {id: `err_${Date.now()}`,role: 'assistant',content: '⚠️ Connection issue. Please ensure the backend is running.',timestamp: Date.now(),}])}setIsLoading(false)}function handleKeyDown(e: React.KeyboardEvent) {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault()sendMessage()}}const statusColor = wsStatus === 'connected' ? '#22c55e' : wsStatus === 'connecting' ? '#f59e0b' : '#ef4444'return (<div className="flex h-full" style={{ background: '#05060d' }}>{/* Left: Chat Panel */}<div className="flex flex-col flex-1 min-w-0">{/* Space Status Bar */}<div className="h-8 flex items-center gap-2 px-3 border-b overflow-x-auto"style={{ borderColor: '#1a1b2e', background: '#07080f' }}>{SPACES_CONFIG.map(s => {const spaceState = spaces[s.id as keyof typeof spaces]const isActive = spaceState?.activereturn (<div key={s.id}className="flex items-center gap-1 px-2 py-0.5 rounded text-[10px] whitespace-nowrap transition-all"style={{background: isActive ? `${s.color}15` : 'transparent',color: isActive ? s.color : '#374151',border: `1px solid ${isActive ? s.color + '30' : 'transparent'}`,}}><span>{s.icon}</span><span className="font-medium">{s.id}</span>{isActive && <span className="w-1 h-1 rounded-full animate-pulse" style={{ background: s.color }} />}</div>)})}<div className="ml-auto flex items-center gap-1 text-[10px]"><div className="w-1.5 h-1.5 rounded-full" style={{ background: statusColor }} /><span style={{ color: statusColor }}>{wsStatus}</span></div></div>{/* Messages */}<div className="flex-1 overflow-y-auto p-4 space-y-4"><AnimatePresence initial={false}>{messages.map(msg => (<motion.divkey={msg.id}initial={{ opacity: 0, y: 10 }}animate={{ opacity: 1, y: 0 }}transition={{ duration: 0.2 }}className={`flex gap-3 ${msg.role === 'user' ? 'flex-row-reverse' : 'flex-row'}`}>{/* Avatar */}<div className={`w-7 h-7 rounded-lg flex-shrink-0 flex items-center justify-center text-sm ${msg.role === 'user'? 'bg-indigo-600': 'bg-gradient-to-br from-violet-600 to-indigo-600'}`}>{msg.role === 'user' ? '👤' : '🤖'}</div>{/* Bubble */}<div className={`max-w-[75%] ${msg.role === 'user' ? 'items-end' : 'items-start'} flex flex-col gap-1`}>{msg.space && (<div className="text-[9px] text-slate-600 px-1">{SPACES_CONFIG.find(s => s.id === msg.space)?.icon} {msg.space?.toUpperCase()} SPACE · {msg.agentRole?.replace('_', ' ')}</div>)}<div className={`px-3 py-2 rounded-2xl text-sm leading-relaxed ${msg.role === 'user'? 'bg-indigo-600 text-white rounded-tr-sm': 'text-slate-200 rounded-tl-sm'}`}style={msg.role === 'assistant' ? { background: '#111827', border: '1px solid #1f2937' } : {}}><div className="whitespace-pre-wrap"dangerouslySetInnerHTML={{__html: msg.content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/```(\w+)?\n?([\s\S]*?)```/g, '<pre class="bg-black/50 p-2 rounded mt-1 overflow-x-auto text-xs"><code>$2</code></pre>').replace(/`(.*?)`/g, '<code class="bg-black/30 px-1 rounded text-xs">$1</code>')}}/></div></div></motion.div>))}</AnimatePresence>{isLoading && (<motion.divinitial={{ opacity: 0 }}animate={{ opacity: 1 }}className="flex gap-3 items-start"><div className="w-7 h-7 rounded-lg bg-gradient-to-br from-violet-600 to-indigo-600 flex items-center justify-center text-sm">🤖</div><div className="px-3 py-2 rounded-2xl rounded-tl-sm" style={{ background: '#111827', border: '1px solid #1f2937' }}><div className="flex items-center gap-2 text-xs text-slate-400"><div className="flex gap-1">{[0,1,2].map(i => (<div key={i} className="w-1.5 h-1.5 rounded-full bg-violet-500 animate-bounce"style={{ animationDelay: `${i * 0.15}s` }} />))}</div>{activeSpaceIndicator? `${SPACES_CONFIG.find(s => s.id === activeSpaceIndicator)?.icon} ${activeSpaceIndicator} Space processing...`: 'Agent Kernel analyzing...'}</div></div></motion.div>)}<div ref={messagesEndRef} /></div>{/* Quick Prompts */}<div className="px-3 pb-2 flex gap-2 overflow-x-auto">{[{ text: '🌐 Search latest AI trends', space: 'browser' },{ text: '🔧 Write a Python API', space: 'coding' },{ text: '💻 Run: print("Hello")', space: 'sandbox' },{ text: '🚀 Generate Dockerfile', space: 'deploy' },{ text: '🐛 Debug my error', space: 'debug' },{ text: '👁️ Create React UI', space: 'vision' },].map((prompt, i) => (<button key={i}onClick={() => { setInput(prompt.text); inputRef.current?.focus() }}className="flex-shrink-0 px-3 py-1.5 rounded-full text-xs text-slate-400 hover:text-slate-200 whitespace-nowrap transition-all"style={{ background: '#0d0e1a', border: '1px solid #1e2035' }}>{prompt.text}</button>))}</div>{/* Input */}<div className="px-3 pb-3"><div className="flex gap-2 p-2 rounded-xl" style={{ background: '#0d0e1a', border: '1px solid #1e2035' }}><textarearef={inputRef}value={input}onChange={e => setInput(e.target.value)}onKeyDown={handleKeyDown}placeholder="Ask anything — I'll route to the right Space automatically..."rows={1}className="flex-1 bg-transparent text-sm text-slate-200 placeholder-slate-600 resize-none outline-none leading-relaxed"style={{ maxHeight: '120px' }}/><buttononClick={sendMessage}disabled={!input.trim() || isLoading}className="p-2 rounded-lg transition-all disabled:opacity-40 flex-shrink-0"style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}><Send size={14} className="text-white" /></button></div><div className="text-[9px] text-slate-700 text-center mt-1">Press Enter to send · Shift+Enter for new line · Powered by Pyae Sone</div></div></div>{/* Right: Space-Role Panel */}<div className="w-64 border-l flex-shrink-0 flex flex-col overflow-y-auto"style={{ borderColor: '#1a1b2e', background: '#07080f' }}>{/* Spaces Grid */}<div className="p-3 border-b" style={{ borderColor: '#1a1b2e' }}><div className="text-[10px] text-slate-600 font-bold uppercase tracking-widest mb-2">Spaces</div><div className="grid grid-cols-2 gap-1.5">{SPACES_CONFIG.map(s => {const spaceState = spaces[s.id as keyof typeof spaces]const isActive = spaceState?.activereturn (<div key={s.id}className="p-2 rounded-lg transition-all cursor-pointer"style={{background: isActive ? `${s.color}10` : 'rgba(255,255,255,0.03)',border: `1px solid ${isActive ? s.color + '40' : '#1e2035'}`,}}><div className="flex items-center justify-between mb-0.5"><span className="text-base">{s.icon}</span>{isActive && (<div className="w-1.5 h-1.5 rounded-full animate-pulse"style={{ background: s.color }} />)}</div><div className="text-[10px] font-semibold" style={{ color: isActive ? s.color : '#475569' }}>{s.name.split(' ')[0]}</div><div className="text-[8px] text-slate-600 mt-0.5">{s.desc}</div>{spaceState?.taskCount > 0 && (<div className="text-[8px] mt-0.5" style={{ color: s.color }}>{spaceState.taskCount} tasks</div>)}</div>)})}</div></div>{/* Roles */}<div className="p-3 border-b" style={{ borderColor: '#1a1b2e' }}><div className="text-[10px] text-slate-600 font-bold uppercase tracking-widest mb-2">Roles</div><div className="space-y-1">{ROLES_CONFIG.map(r => (<div key={r.id}className="flex items-center gap-2 p-1.5 rounded-lg transition-all"style={{background: currentRole === r.id ? 'rgba(139,92,246,0.1)' : 'transparent',border: `1px solid ${currentRole === r.id ? 'rgba(139,92,246,0.3)' : 'transparent'}`,}}><span className="text-sm">{r.icon}</span><div><div className="text-[10px] font-semibold" style={{ color: currentRole === r.id ? '#a78bfa' : '#475569' }}>{r.name}</div><div className="text-[8px] text-slate-600">{r.desc}</div></div></div>))}</div></div>{/* System Status */}<div className="p-3"><div className="text-[10px] text-slate-600 font-bold uppercase tracking-widest mb-2">System</div><div className="space-y-1.5">{[{ label: 'Agent Kernel', status: 'operational', color: '#22c55e' },{ label: 'AI Router', status: 'active', color: '#22c55e' },{ label: 'Memory', status: 'ready', color: '#22c55e' },{ label: 'WebSocket', status: wsStatus, color: statusColor },].map(item => (<div key={item.label} className="flex items-center justify-between"><span className="text-[10px] text-slate-500">{item.label}</span><div className="flex items-center gap-1"><div className="w-1.5 h-1.5 rounded-full" style={{ background: item.color }} /><span className="text-[9px]" style={{ color: item.color }}>{item.status}</span></div></div>))}</div></div></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267'use client'
import { useState, useEffect } from 'react'import { motion } from 'framer-motion'import { Play, RefreshCw } from 'lucide-react'import { useAppStore } from '@/store/useAppStore'
const SPACES_DETAIL = [ { id: 'core', name: 'Core Space', icon: '🧠', color: '#7c3aed', description: 'The central nervous system. Manages memory, planning, and overall orchestration.', tools: ['Goal decomposition', 'Long-term memory access', 'Task delegation', 'Context management'], roles: ['Cognition', 'Automation'], phase: 'Phase 1', }, { id: 'browser', name: 'Browser Space', icon: '🌐', color: '#2563eb', description: 'The interface to the web. Handles all internet-based research and interaction.', tools: ['Web navigation', 'DOM parsing', 'Data extraction', 'Form filling'], roles: ['Automation', 'Cognition'], phase: 'Phase 3', }, { id: 'sandbox', name: 'Sandbox Space', icon: '💻', color: '#059669', description: 'Secure execution environment. Where code is run and tested safely.', tools: ['Python interpreter', 'Node.js runtime', 'Shell access', 'Isolated filesystem'], roles: ['Execution', 'Cognition'], phase: 'Phase 3', }, { id: 'coding', name: 'Coding Space', icon: '🔧', color: '#d97706', description: 'The development environment. Focused on code generation and manipulation.', tools: ['Multi-language codegen', 'Code review', 'Refactoring', 'Test generation'], roles: ['Execution', 'Cognition', 'Automation'], phase: 'Phase 3', }, { id: 'vision', name: 'Vision Space', icon: '👁️', color: '#db2777', description: 'Visual processing domain. Handles image understanding and UI generation.', tools: ['UI generation', 'Image analysis', 'Design-to-code', 'OCR'], roles: ['Visual Intelligence', 'Execution'], phase: 'Phase 3', }, { id: 'debug', name: 'Debug Space', icon: '🐛', color: '#dc2626', description: 'Diagnostic environment. Analyzes errors and proposes self-healing solutions.', tools: ['Stack trace analysis', 'Log parsing', 'Error classification', 'Self-healing'], roles: ['Repair', 'Cognition'], phase: 'Phase 3', }, { id: 'deploy', name: 'Deploy Space', icon: '🚀', color: '#0891b2', description: 'Infrastructure domain. Manages cloud deployments and CI/CD pipelines.', tools: ['Vercel deploy', 'Docker config', 'GitHub Actions', 'HuggingFace Spaces'], roles: ['Automation', 'Execution'], phase: 'Phase 3', }, { id: 'communication', name: 'Communication Space', icon: '💬', color: '#8b5cf6', description: 'Interaction domain. Manages documentation, email, and multi-channel messaging.', tools: ['Email drafting', 'Documentation', 'Report creation', 'Translation'], roles: ['Automation', 'Cognition'], phase: 'Phase 2', },]
export default function SpacesPage() { const { spaces, activeSpace } = useAppStore() const [selectedSpace, setSelectedSpace] = useState<string | null>(null) const [testTask, setTestTask] = useState('') const [testResult, setTestResult] = useState('') const [testing, setTesting] = useState(false)
async function testSpace(spaceId: string) { if (!testTask.trim()) return setTesting(true) setTestResult('') try { const res = await fetch(`/api/v1/spaces/${spaceId}/execute`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ task: testTask, role: 'cognition', session_id: 'spaces_test' }), }) if (res.ok) { const data = await res.json() setTestResult(data.result || 'No result') } else { setTestResult(`Error: ${res.status} ${res.statusText}`) } } catch (e: any) { setTestResult(`Connection error: ${e.message}`) } setTesting(false) }
return ( <div className="h-full overflow-y-auto p-6" style={{ background: '#05060d' }}> <div className="max-w-6xl mx-auto"> {/* Header */} <div className="mb-6"> <h1 className="text-2xl font-bold text-white mb-1">Space-Role Architecture</h1> <p className="text-slate-500 text-sm">8 Spaces × 5 Roles = Infinite capability combinations</p> </div>
{/* Architecture Diagram */} <div className="mb-6 p-4 rounded-xl border" style={{ background: '#07080f', borderColor: '#1e2035' }}> <div className="text-[10px] text-slate-600 font-bold uppercase tracking-widest mb-3">Architecture Overview</div> <div className="flex items-center justify-center gap-3 flex-wrap"> <div className="px-3 py-2 rounded-lg text-xs font-semibold text-violet-300" style={{ background: 'rgba(139,92,246,0.15)', border: '1px solid rgba(139,92,246,0.3)' }}> 🧠 Agent Kernel </div> <div className="text-slate-600">→</div> <div className="px-3 py-2 rounded-lg text-xs font-semibold text-blue-300" style={{ background: 'rgba(37,99,235,0.15)', border: '1px solid rgba(37,99,235,0.3)' }}> 🎯 Intent Classifier </div> <div className="text-slate-600">→</div> <div className="px-3 py-2 rounded-lg text-xs font-semibold text-green-300" style={{ background: 'rgba(5,150,105,0.15)', border: '1px solid rgba(5,150,105,0.3)' }}> 📦 Space Router </div> <div className="text-slate-600">→</div> <div className="px-3 py-2 rounded-lg text-xs font-semibold text-orange-300" style={{ background: 'rgba(217,119,6,0.15)', border: '1px solid rgba(217,119,6,0.3)' }}> 🎭 Role Assignment </div> <div className="text-slate-600">→</div> <div className="px-3 py-2 rounded-lg text-xs font-semibold text-pink-300" style={{ background: 'rgba(219,39,119,0.15)', border: '1px solid rgba(219,39,119,0.3)' }}> 🛠️ Tool Execution </div> </div> </div>
{/* Spaces Grid */} <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 mb-6"> {SPACES_DETAIL.map((space, i) => { const spaceState = spaces[space.id as keyof typeof spaces] const isActive = spaceState?.active const isSelected = selectedSpace === space.id return ( <motion.div key={space.id} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }} onClick={() => setSelectedSpace(isSelected ? null : space.id)} className="p-4 rounded-xl border cursor-pointer transition-all hover:scale-[1.02]" style={{ background: isSelected ? `${space.color}10` : '#07080f', borderColor: isSelected ? `${space.color}50` : isActive ? `${space.color}30` : '#1e2035', }}> <div className="flex items-center justify-between mb-3"> <span className="text-2xl">{space.icon}</span> <div className="flex items-center gap-1"> <span className="text-[9px] px-1.5 py-0.5 rounded" style={{ background: `${space.color}20`, color: space.color }}> {space.phase} </span> {isActive && ( <div className="w-1.5 h-1.5 rounded-full animate-pulse" style={{ background: space.color }} /> )} </div> </div> <h3 className="text-sm font-bold text-white mb-1">{space.name}</h3> <p className="text-[10px] text-slate-500 mb-3 leading-relaxed">{space.description}</p> <div className="space-y-2"> <div> <div className="text-[9px] text-slate-700 mb-1">TOOLS</div> <div className="flex flex-wrap gap-1"> {space.tools.slice(0, 2).map(tool => ( <span key={tool} className="text-[8px] px-1.5 py-0.5 rounded" style={{ background: '#0d0e1a', color: '#475569', border: '1px solid #1e2035' }}> {tool} </span> ))} </div> </div> <div className="flex items-center justify-between"> <div className="text-[9px] text-slate-700"> ROLES: <span style={{ color: space.color }}>{space.roles.join(', ')}</span> </div> {spaceState?.taskCount > 0 && ( <span className="text-[9px]" style={{ color: space.color }}> {spaceState.taskCount} tasks </span> )} </div> </div> </motion.div> ) })} </div>
{/* Space Tester */} {selectedSpace && ( <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="p-4 rounded-xl border" style={{ background: '#07080f', borderColor: `${SPACES_DETAIL.find(s => s.id === selectedSpace)?.color}40` }}> <div className="text-sm font-bold text-white mb-3"> Test {SPACES_DETAIL.find(s => s.id === selectedSpace)?.icon} {selectedSpace} Space </div> <div className="flex gap-2 mb-3"> <input value={testTask} onChange={e => setTestTask(e.target.value)} placeholder={`Enter a task for ${selectedSpace} space...`} className="flex-1 px-3 py-2 rounded-lg text-sm text-slate-200 bg-black/20 outline-none" style={{ border: '1px solid #1e2035' }} onKeyDown={e => e.key === 'Enter' && testSpace(selectedSpace)} /> <button onClick={() => testSpace(selectedSpace)} disabled={testing || !testTask.trim()} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white disabled:opacity-50 transition-all" style={{ background: SPACES_DETAIL.find(s => s.id === selectedSpace)?.color }}> {testing ? <RefreshCw size={14} className="animate-spin" /> : <Play size={14} />} {testing ? 'Running...' : 'Execute'} </button> </div> {testResult && ( <div className="p-3 rounded-lg text-xs text-slate-300 whitespace-pre-wrap" style={{ background: '#0a0b14', border: '1px solid #1e2035' }}> {testResult} </div> )} </motion.div> )} </div> </div> )}2 unmodified lines34567892 unmodified linesimport { useState } from 'react'import { motion } from 'framer-motion'import { CheckSquare, Clock, Loader2, AlertCircle, Plus, ChevronRight } from 'lucide-react'import { TASKS, Task } from '@/store/useAppStore'import { cn } from '@/lib/utils'const STATUS_CONFIG = {2 unmodified lines3456789102 unmodified linesimport { useState } from 'react'import { motion } from 'framer-motion'import { CheckSquare, Clock, Loader2, AlertCircle, Plus, ChevronRight } from 'lucide-react'type Task = { id: string; title: string; status: 'running' | 'completed' | 'pending' | 'failed'; space?: string; agent?: string; goal: string; started?: number; completed_at?: number }const TASKS: Task[] = []import { cn } from '@/lib/utils'const STATUS_CONFIG = {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142'use client'import { motion, AnimatePresence } from 'framer-motion'import {LayoutDashboard, Bot, CheckSquare, Brain, BookOpen,GitBranch, BarChart3, Settings, ChevronLeft, Zap,Activity, Menu, X} from 'lucide-react'import { useAppStore, NavPage } from '@/store/useAppStore'import { cn } from '@/lib/utils'const NAV_ITEMS: { page: NavPage; label: string; icon: React.ElementType; badge?: string }[] = [{ page: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },{ page: 'agents', label: 'Agents', icon: Bot, badge: '12' },{ page: 'tasks', label: 'Tasks', icon: CheckSquare, badge: '3' },{ page: 'memory', label: 'Memory', icon: Brain },{ page: 'knowledge', label: 'Knowledge', icon: BookOpen },{ page: 'workflows', label: 'Workflows', icon: GitBranch },{ page: 'analytics', label: 'Analytics', icon: BarChart3 },{ page: 'settings', label: 'Settings', icon: Settings },]export default function Sidebar() {const { currentPage, setCurrentPage, sidebarCollapsed, toggleSidebar, godModeActive, toggleGodMode } = useAppStore()return (<motion.asideanimate={{ width: sidebarCollapsed ? 64 : 220 }}transition={{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }}className="flex flex-col h-full flex-shrink-0 border-r overflow-hidden"style={{ borderColor: 'var(--border)', background: 'rgba(10,12,22,0.95)', backdropFilter: 'blur(20px)' }}>{/* Logo */}<div className="flex items-center gap-3 px-4 py-5 border-b" style={{ borderColor: 'var(--border)' }}><div className="relative flex-shrink-0"><div className="w-8 h-8 rounded-xl flex items-center justify-center glow-purple"style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}><Zap size={16} className="text-white" /></div>{godModeActive && (<div className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-green-400 border-2 border-[#0a0c16]" />)}</div><AnimatePresence>{!sidebarCollapsed && (<motion.divinitial={{ opacity: 0, x: -8 }}animate={{ opacity: 1, x: 0 }}exit={{ opacity: 0, x: -8 }}transition={{ duration: 0.2 }}className="min-w-0"><div className="text-sm font-bold text-white leading-none">GOD AGENT OS</div><div className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>by manus + genspark</div></motion.div>)}</AnimatePresence><buttononClick={toggleSidebar}className="ml-auto text-slate-500 hover:text-slate-300 transition-colors flex-shrink-0">{sidebarCollapsed ? <Menu size={16} /> : <ChevronLeft size={16} />}</button></div>{/* Navigation */}<nav className="flex-1 overflow-y-auto py-3 px-2 space-y-0.5">{NAV_ITEMS.map(({ page, label, icon: Icon, badge }) => {const isActive = currentPage === pagereturn (<buttonkey={page}onClick={() => setCurrentPage(page)}className={cn('nav-item w-full text-left relative group',isActive && 'active')}title={sidebarCollapsed ? label : undefined}><Icon size={17} className="flex-shrink-0" style={{ color: isActive ? '#a78bfa' : undefined }} /><AnimatePresence>{!sidebarCollapsed && (<motion.spaninitial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}className="flex-1 text-left">{label}</motion.span>)}</AnimatePresence>{badge && !sidebarCollapsed && (<span className="ml-auto text-xs px-1.5 py-0.5 rounded-full font-semibold"style={{ background: isActive ? 'rgba(124,58,237,0.3)' : 'rgba(255,255,255,0.07)', color: isActive ? '#c084fc' : 'var(--text-muted)' }}>{badge}</span>)}</button>)})}</nav>{/* System Status */}<div className="px-2 pb-2"><div className="border-t mb-2" style={{ borderColor: 'var(--border)' }} />{!sidebarCollapsed && (<div className="px-2 mb-2"><div className="flex items-center gap-2 mb-1"><Activity size={11} className="text-green-400" /><span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>System Status</span></div><div className="flex items-center gap-2"><div className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse-glow" /><span className="text-xs text-green-400 font-medium">All Systems Operational</span></div></div>)}{/* God Mode Toggle */}<div className={cn('flex items-center gap-2 px-2 py-2 rounded-xl cursor-pointer transition-all',sidebarCollapsed ? 'justify-center' : '',godModeActive ? 'glass-purple' : 'glass')} onClick={toggleGodMode}><div className={cn('w-6 h-3.5 rounded-full relative transition-all flex-shrink-0',godModeActive ? 'bg-purple-600' : 'bg-slate-700')}><div className={cn('absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all',godModeActive ? 'right-0.5 bg-white' : 'left-0.5 bg-slate-400')} /></div>{!sidebarCollapsed && (<span className="text-xs font-semibold" style={{ color: godModeActive ? '#a78bfa' : 'var(--text-muted)' }}>God Mode {godModeActive ? 'ON' : 'OFF'}</span>)}</div></div></motion.aside>)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122'use client'import {LayoutDashboard, Box, Bot, ListTodo, Brain,BookOpen, GitBranch, BarChart2, Settings,Zap, Globe, Terminal, Code2, Eye, Bug,Rocket, MessageSquare, Plug} from 'lucide-react'import { useAppStore } from '@/store/useAppStore'import type { Page } from '@/store/useAppStore'const NAV_ITEMS: { id: Page; label: string; icon: any; group?: string }[] = [{ id: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },{ id: 'spaces', label: 'Spaces', icon: Box },{ id: 'agents', label: 'Agents', icon: Bot },{ id: 'connectors', label: 'Connectors', icon: Plug },{ id: 'tasks', label: 'Tasks', icon: ListTodo },{ id: 'memory', label: 'Memory', icon: Brain },{ id: 'knowledge', label: 'Knowledge', icon: BookOpen },{ id: 'workflows', label: 'Workflows', icon: GitBranch },{ id: 'analytics', label: 'Analytics', icon: BarChart2 },{ id: 'settings', label: 'Settings', icon: Settings },]const SPACES = [{ id: 'core', label: 'Core', icon: '🧠', color: '#7c3aed' },{ id: 'browser', label: 'Browser', icon: '🌐', color: '#2563eb' },{ id: 'sandbox', label: 'Sandbox', icon: '💻', color: '#059669' },{ id: 'coding', label: 'Coding', icon: '🔧', color: '#d97706' },{ id: 'vision', label: 'Vision', icon: '👁️', color: '#db2777' },{ id: 'debug', label: 'Debug', icon: '🐛', color: '#dc2626' },{ id: 'deploy', label: 'Deploy', icon: '🚀', color: '#0891b2' },{ id: 'communication', label: 'Comm', icon: '💬', color: '#7c3aed' },]export default function Sidebar() {const { currentPage, setCurrentPage, sidebarOpen, spaces, activeSpace } = useAppStore()if (!sidebarOpen) return nullreturn (<aside className="w-52 flex-shrink-0 flex flex-col border-r h-full overflow-y-auto"style={{ background: 'var(--bg-1, #07080f)', borderColor: 'var(--border, #1e2035)' }}>{/* Brand */}<div className="p-3 border-b" style={{ borderColor: '#1e2035' }}><div className="flex items-center gap-2"><div className="w-8 h-8 rounded-xl bg-gradient-to-br from-violet-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-violet-500/20"><Zap size={16} className="text-white" /></div><div><div className="text-xs font-bold text-white">GOD AGENT OS</div><div className="text-[9px] text-violet-400 font-medium">v9 · Space-Role</div></div></div></div>{/* Navigation */}<nav className="p-2 flex-1"><div className="space-y-0.5">{NAV_ITEMS.map(item => {const Icon = item.iconconst active = currentPage === item.idreturn (<buttonkey={item.id}onClick={() => setCurrentPage(item.id)}className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all ${active? 'bg-violet-500/15 text-violet-300 border border-violet-500/20': 'text-slate-500 hover:text-slate-300 hover:bg-white/4'}`}><Icon size={13} />{item.label}</button>)})}</div>{/* Spaces Section */}<div className="mt-4"><div className="px-2 mb-2 text-[9px] font-bold text-slate-600 uppercase tracking-widest">Active Spaces</div><div className="grid grid-cols-2 gap-1">{SPACES.map(s => {const isActive = spaces[s.id as keyof typeof spaces]?.activeconst isSelected = activeSpace === s.idreturn (<divkey={s.id}className="flex flex-col items-center p-1.5 rounded-lg text-center transition-all cursor-pointer"style={{background: isActive ? `${s.color}15` : 'rgba(255,255,255,0.03)',border: `1px solid ${isActive ? s.color + '40' : 'transparent'}`,}}><span className="text-sm">{s.icon}</span><span className="text-[8px] mt-0.5" style={{ color: isActive ? s.color : '#475569' }}>{s.label}</span>{isActive && (<div className="w-1 h-1 rounded-full mt-0.5 animate-pulse"style={{ background: s.color }} />)}</div>)})}</div></div></nav>{/* Footer */}<div className="p-3 border-t" style={{ borderColor: '#1e2035' }}><div className="text-[9px] text-slate-600 text-center">Powered by <span className="text-violet-500 font-semibold">Pyae Sone</span></div></div></aside>)}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181'use client'import { useState, useEffect, useRef } from 'react'import { motion, AnimatePresence } from 'framer-motion'import { Search, Bell, Command, Sparkles, X, ArrowRight, Bot, CheckSquare, FileText, Zap } from 'lucide-react'import { useAppStore } from '@/store/useAppStore'const QUICK_COMMANDS = [{ icon: Bot, label: 'New Research Task', shortcut: '/research', page: 'agents' as const },{ icon: CheckSquare, label: 'View Running Tasks', shortcut: '/tasks', page: 'tasks' as const },{ icon: FileText, label: 'Generate Report', shortcut: '/report', page: 'analytics' as const },{ icon: Zap, label: 'Deploy Application', shortcut: '/deploy', page: 'workflows' as const },]const NOTIFICATIONS = [{ id: '1', title: 'Code Agent', message: 'Successfully deployed production API', time: '2m ago', color: '#34d399' },{ id: '2', title: 'Research Agent', message: 'Market analysis complete — 47 insights found', time: '15m ago', color: '#6366f1' },{ id: '3', title: 'Data Agent', message: 'Processed 1.2M data points', time: '1h ago', color: '#22d3ee' },]export default function TopBar() {const { setCurrentPage, commandPaletteOpen, setCommandPaletteOpen } = useAppStore()const [query, setQuery] = useState('')const [notifOpen, setNotifOpen] = useState(false)const inputRef = useRef<HTMLInputElement>(null)useEffect(() => {const handler = (e: KeyboardEvent) => {if ((e.metaKey || e.ctrlKey) && e.key === 'k') {e.preventDefault()setCommandPaletteOpen(true)setTimeout(() => inputRef.current?.focus(), 50)}if (e.key === 'Escape') {setCommandPaletteOpen(false)setNotifOpen(false)setQuery('')}}window.addEventListener('keydown', handler)return () => window.removeEventListener('keydown', handler)}, [setCommandPaletteOpen])const filtered = QUICK_COMMANDS.filter(c =>query === '' || c.label.toLowerCase().includes(query.toLowerCase()) || c.shortcut.includes(query))return (<header className="flex items-center gap-4 px-4 py-3 border-b flex-shrink-0 relative z-30"style={{ borderColor: 'var(--border)', background: 'rgba(10,12,22,0.98)', backdropFilter: 'blur(20px)' }}>{/* Search / Command Trigger */}<div className="flex-1 max-w-xl mx-auto"><buttononClick={() => { setCommandPaletteOpen(true); setTimeout(() => inputRef.current?.focus(), 50) }}className="w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-left transition-all hover:border-purple-500/30"style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)' }}><Search size={15} className="text-slate-500 flex-shrink-0" /><span className="flex-1 text-sm" style={{ color: 'var(--text-muted)' }}>Search agents, tasks, docs…</span><div className="flex items-center gap-1 text-xs px-1.5 py-0.5 rounded-md"style={{ background: 'rgba(255,255,255,0.06)', color: 'var(--text-muted)' }}><Command size={10} /><span>K</span></div></button></div>{/* Right Icons */}<div className="flex items-center gap-2"><button className="p-2 rounded-xl text-slate-500 hover:text-slate-300 hover:bg-white/5 transition-all"><Sparkles size={17} /></button>{/* Notifications */}<div className="relative"><buttononClick={() => setNotifOpen(!notifOpen)}className="relative p-2 rounded-xl text-slate-500 hover:text-slate-300 hover:bg-white/5 transition-all"><Bell size={17} /><div className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-purple-500 border border-[#0a0c16]" /></button><AnimatePresence>{notifOpen && (<motion.divinitial={{ opacity: 0, y: 8, scale: 0.95 }}animate={{ opacity: 1, y: 0, scale: 1 }}exit={{ opacity: 0, y: 8, scale: 0.95 }}transition={{ duration: 0.2 }}className="absolute right-0 top-full mt-2 w-80 glass-card overflow-hidden z-50"><div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: 'var(--border)' }}><span className="text-sm font-semibold text-white">Notifications</span><button onClick={() => setNotifOpen(false)} className="text-slate-500 hover:text-slate-300"><X size={14} /></button></div>{NOTIFICATIONS.map((n) => (<div key={n.id} className="flex gap-3 px-4 py-3 hover:bg-white/[0.03] transition-colors cursor-pointer border-b last:border-0"style={{ borderColor: 'var(--border)' }}><div className="w-2 h-2 rounded-full flex-shrink-0 mt-1.5" style={{ background: n.color }} /><div className="min-w-0"><div className="text-xs font-semibold text-white">{n.title}</div><div className="text-xs mt-0.5 text-slate-400 line-clamp-1">{n.message}</div><div className="text-xs mt-1 text-slate-600">{n.time}</div></div></div>))}</motion.div>)}</AnimatePresence></div>{/* Avatar */}<div className="w-8 h-8 rounded-full overflow-hidden border-2 cursor-pointer"style={{ borderColor: 'rgba(124,58,237,0.4)', background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}><div className="w-full h-full flex items-center justify-center text-xs font-bold text-white">A</div></div></div>{/* Command Palette Modal */}<AnimatePresence>{commandPaletteOpen && (<><motion.divinitial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50"onClick={() => { setCommandPaletteOpen(false); setQuery('') }}/><motion.divinitial={{ opacity: 0, scale: 0.96, y: -16 }}animate={{ opacity: 1, scale: 1, y: 0 }}exit={{ opacity: 0, scale: 0.96, y: -16 }}transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}className="fixed top-[20vh] left-1/2 -translate-x-1/2 w-full max-w-lg glass-card z-50 overflow-hidden"><div className="flex items-center gap-3 px-4 py-3.5 border-b" style={{ borderColor: 'var(--border)' }}><Search size={16} className="text-slate-500" /><inputref={inputRef}value={query}onChange={e => setQuery(e.target.value)}placeholder="Search agents, run commands…"className="flex-1 bg-transparent text-sm text-white placeholder:text-slate-500 outline-none"/><button onClick={() => { setCommandPaletteOpen(false); setQuery('') }}className="text-slate-500 hover:text-slate-300 transition-colors"><X size={14} /></button></div><div className="py-2 max-h-64 overflow-y-auto">{filtered.map(({ icon: Icon, label, shortcut, page }) => (<button key={label}onClick={() => { setCurrentPage(page); setCommandPaletteOpen(false); setQuery('') }}className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-white/[0.04] transition-colors group"><Icon size={15} className="text-purple-400 group-hover:text-purple-300" /><span className="flex-1 text-sm text-left text-slate-300 group-hover:text-white">{label}</span><span className="text-xs font-mono px-2 py-0.5 rounded"style={{ background: 'rgba(255,255,255,0.06)', color: 'var(--text-muted)' }}>{shortcut}</span><ArrowRight size={13} className="text-slate-600 group-hover:text-purple-400 transition-colors" /></button>))}{filtered.length === 0 && (<div className="px-4 py-6 text-center text-sm text-slate-600">No results for "{query}"</div>)}</div><div className="px-4 py-2 border-t flex items-center gap-4 text-xs text-slate-600"style={{ borderColor: 'var(--border)' }}><span>↑↓ navigate</span><span>↵ select</span><span>esc close</span></div></motion.div></>)}</AnimatePresence></header>)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394'use client'import { useState } from 'react'import { Menu, Zap, Settings, Bell, Activity } from 'lucide-react'import { useAppStore } from '@/store/useAppStore'const SPACE_COLORS: Record<string, string> = {core: '#7c3aed',browser: '#2563eb',sandbox: '#059669',coding: '#d97706',vision: '#db2777',debug: '#dc2626',deploy: '#0891b2',communication: '#7c3aed',}export default function TopBar() {const { sidebarOpen, setSidebarOpen, activeSpace, currentRole, spaces } = useAppStore()const activeSpaces = Object.values(spaces).filter(s => s.active)return (<header className="h-12 flex items-center justify-between px-3 border-b shrink-0"style={{ background: 'var(--bg-2, #0a0b14)', borderColor: 'var(--border, #1e2035)' }}>{/* Left */}<div className="flex items-center gap-3"><button onClick={() => setSidebarOpen(!sidebarOpen)}className="p-1.5 rounded-lg hover:bg-white/5 transition-colors"><Menu size={16} className="text-slate-400" /></button><div className="flex items-center gap-2"><div className="w-7 h-7 rounded-lg bg-gradient-to-br from-violet-600 to-indigo-600 flex items-center justify-center shadow-lg"><Zap size={14} className="text-white" /></div><div className="hidden sm:block"><span className="text-sm font-bold text-white">GOD AGENT OS</span><span className="text-[10px] ml-1.5 px-1.5 py-0.5 rounded-full text-violet-300 font-semibold"style={{ background: 'rgba(139,92,246,0.15)', border: '1px solid rgba(139,92,246,0.3)' }}>v9 Space-Role</span></div></div></div>{/* Center — Active Space indicator */}<div className="hidden md:flex items-center gap-2">{activeSpace ? (<div className="flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium"style={{background: `${SPACE_COLORS[activeSpace]}20`,border: `1px solid ${SPACE_COLORS[activeSpace]}40`,color: SPACE_COLORS[activeSpace],}}><div className="w-1.5 h-1.5 rounded-full animate-pulse"style={{ background: SPACE_COLORS[activeSpace] }} />{spaces[activeSpace]?.icon} {activeSpace.toUpperCase()} SPACE — {currentRole.replace('_', ' ').toUpperCase()}</div>) : (<div className="flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium"style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#64748b' }}><div className="w-1.5 h-1.5 rounded-full bg-slate-500" />8 Spaces Ready</div>)}{activeSpaces.length > 0 && (<div className="flex gap-1">{activeSpaces.slice(0, 3).map(s => (<div key={s.name} className="w-2 h-2 rounded-full animate-pulse"style={{ background: SPACE_COLORS[s.name] }} />))}</div>)}</div>{/* Right */}<div className="flex items-center gap-1"><div className="flex items-center gap-1.5 px-2 py-1 rounded text-xs text-slate-500"><Activity size={11} className="text-green-400" /><span className="hidden sm:inline text-green-400 font-medium">Powered by Pyae Sone</span></div><button className="p-1.5 rounded-lg hover:bg-white/5 transition-colors"><Bell size={15} className="text-slate-500" /></button><button className="p-1.5 rounded-lg hover:bg-white/5 transition-colors"><Settings size={15} className="text-slate-500" /></button></div></header>)}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163/*** God Mode+ API Client*/const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://pyae1994-autonomous-coding-system.hf.space'async function apiFetch(path: string, options?: RequestInit) {const res = await fetch(`${API_URL}${path}`, {headers: { 'Content-Type': 'application/json' },...options,})if (!res.ok) throw new Error(`API ${res.status}: ${await res.text()}`)return res.json()}// ─── Tasks ────────────────────────────────────────────────────────────────────export async function createTask(goal: string, sessionId: string, options?: {githubRepo?: stringautoCommit?: booleanmetadata?: Record<string, any>}) {return apiFetch('/api/v1/tasks/', {method: 'POST',body: JSON.stringify({goal,session_id: sessionId,github_repo: options?.githubRepo || '',auto_commit: options?.autoCommit || false,metadata: options?.metadata || {},}),})}export async function getTask(taskId: string) {return apiFetch(`/api/v1/tasks/${taskId}`)}export async function getTasks(sessionId?: string, limit = 50) {const q = sessionId ? `?session_id=${sessionId}&limit=${limit}` : `?limit=${limit}`return apiFetch(`/api/v1/tasks/${q}`)}export async function cancelTask(taskId: string) {return apiFetch(`/api/v1/tasks/${taskId}/cancel`, { method: 'POST' })}export async function retryTask(taskId: string) {return apiFetch(`/api/v1/tasks/${taskId}/retry`, { method: 'POST' })}export async function getTaskEvents(taskId: string) {return apiFetch(`/api/v1/tasks/${taskId}/events`)}// ─── Chat ─────────────────────────────────────────────────────────────────────export async function streamChatSSE(messages: Array<{ role: string; content: string }>,sessionId: string,onChunk: (chunk: string) => void,onComplete: (full: string) => void,onError: (err: string) => void,) {try {const res = await fetch(`${API_URL}/api/v1/chat/stream`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ messages, session_id: sessionId }),})if (!res.ok) throw new Error(`${res.status}`)if (!res.body) throw new Error('No body')const reader = res.body.getReader()const dec = new TextDecoder()let full = ''while (true) {const { done, value } = await reader.read()if (done) breakconst text = dec.decode(value, { stream: true })for (const line of text.split('\n')) {if (!line.startsWith('data:')) continueconst data = line.slice(5).trim()if (data === '[DONE]') { onComplete(full); return }try {const obj = JSON.parse(data)const chunk = obj.chunk || obj.content || obj.delta || ''if (chunk) { full += chunk; onChunk(chunk) }} catch {}}}onComplete(full)} catch (e: any) {onError(e.message)}}// ─── Orchestrator ─────────────────────────────────────────────────────────────export async function orchestrate(message: string, sessionId: string, context?: Record<string, any>) {return apiFetch('/api/v1/agents/orchestrate', {method: 'POST',body: JSON.stringify({ message, session_id: sessionId, context: context || {} }),})}// ─── Memory ───────────────────────────────────────────────────────────────────export async function getMemory(sessionId: string, limit = 20) {return apiFetch(`/api/v1/memory/?session_id=${sessionId}&limit=${limit}`)}export async function searchMemory(query: string, sessionId?: string) {const q = sessionId ? `?q=${encodeURIComponent(query)}&session_id=${sessionId}` : `?q=${encodeURIComponent(query)}`return apiFetch(`/api/v1/memory/search${q}`)}// ─── Connectors ────────────────────────────────────────────────────────────��──export async function getConnectors() {return apiFetch('/api/v1/connectors/')}export async function getConnectorSummary() {return apiFetch('/api/v1/connectors/summary')}export async function setConnectorToken(connectorId: string, token: string) {return apiFetch('/api/v1/connectors/set-token', {method: 'POST',body: JSON.stringify({ connector_id: connectorId, token }),})}// ─── Sandbox ──────────────────────────────────────────────────────────────────export async function sandboxExecute(command: string, cwd?: string) {return apiFetch('/api/v1/agents/sandbox/execute', {method: 'POST',body: JSON.stringify({ command, cwd: cwd || '' }),})}export async function sandboxWriteFile(filename: string, content: string) {return apiFetch('/api/v1/agents/sandbox/file', {method: 'POST',body: JSON.stringify({ filename, content }),})}export async function getWorkspaceInfo() {return apiFetch('/api/v1/agents/sandbox/workspace')}// ─── AI Router ────────────────────────────────────────────────────────────────export async function getAIRouterStats() {return apiFetch('/api/v1/agents/ai-router/stats')}// ─── GitHub ───────────────────────────────────────────────────────────────────export async function getGitHubStatus() {return apiFetch('/api/v1/github/status')}// ─── Health ───────────────────────────────────────────────────────────────────export async function getHealth() {return apiFetch('/api/v1/health')}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7860'const WS_BASE = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:7860'export const API_URL = API_BASEexport const WS_URL = WS_BASEexport async function fetchAPI(path: string, options?: RequestInit) {const res = await fetch(`${API_BASE}${path}`, {headers: { 'Content-Type': 'application/json' },...options,})if (!res.ok) throw new Error(`API error: ${res.status}`)return res.json()}export async function getKernelStatus() {return fetchAPI('/api/v1/kernel/status')}export async function getSpaces() {return fetchAPI('/api/v1/spaces')}export async function executeInSpace(spaceName: string, task: string, role: string, sessionId: string) {return fetchAPI(`/api/v1/spaces/${spaceName}/execute`, {method: 'POST',body: JSON.stringify({ task, role, session_id: sessionId }),})}export async function orchestrate(message: string, sessionId: string, context?: object) {return fetchAPI('/api/v1/kernel/orchestrate', {method: 'POST',body: JSON.stringify({ message, session_id: sessionId, context }),})}export async function getConnectors() {return fetchAPI('/api/v1/connectors')}export async function getHealth() {return fetchAPI('/api/v1/health')}export async function getTasks() {return fetchAPI('/api/v1/tasks/')}export async function getMemory() {return fetchAPI('/api/v1/memory/')}export function createWebSocket(path: string): WebSocket {return new WebSocket(`${WS_BASE}${path}`)}
12345678910111213141516/** @type {import('next').NextConfig} */const nextConfig = {reactStrictMode: true,env: {NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'https://pyae1994-autonomous-coding-system.hf.space',NEXT_PUBLIC_WS_URL: process.env.NEXT_PUBLIC_WS_URL || 'wss://pyae1994-autonomous-coding-system.hf.space',NEXT_PUBLIC_VSCODE_URL: 'https://pyae1994-god-agent-vscode.hf.space',},async rewrites() {return [{source: '/api/backend/:path*',destination: `${process.env.NEXT_PUBLIC_API_URL || 'https://pyae1994-autonomous-coding-system.hf.space'}/api/:path*`,},]},1234567891011121314151617181920212223242526272829/** @type {import('next').NextConfig} */const nextConfig = {reactStrictMode: false,poweredByHeader: false,async rewrites() {const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7860'return [{source: '/api/v1/:path*',destination: `${backendUrl}/api/v1/:path*`,},{source: '/ws/:path*',destination: `${backendUrl}/ws/:path*`,},]},async headers() {return [{source: '/(.*)',headers: [{ key: 'X-Powered-By', value: 'Pyae Sone - GOD AGENT OS v9' },],},]},
123456789101112{"name": "god-mode-plus-ui","version": "3.0.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "god-mode-plus-ui","version": "3.0.0","dependencies": {"@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-dropdown-menu": "^2.1.16",123456789101112{"name": "god-agent-os-ui","version": "8.0.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "god-agent-os-ui","version": "8.0.0","dependencies": {"@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-dropdown-menu": "^2.1.16",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import { create } from 'zustand'import { persist } from 'zustand/middleware'export type NavPage = 'dashboard' | 'agents' | 'tasks' | 'memory' | 'knowledge' | 'workflows' | 'analytics' | 'settings'export interface Agent {id: stringname: stringrole: stringstatus: 'active' | 'idle' | 'processing' | 'error'color: stringicon: stringtasks: numberefficiency: numberuptime: numberlastAction: stringlastActionTime: string}export interface Task {id: stringtitle: stringstatus: 'running' | 'completed' | 'pending' | 'failed'agent: stringprogress: numbercreatedAt: stringcompletedAt?: string}export interface ActivityItem {id: stringagent: stringaction: stringtime: stringtype: 'success' | 'processing' | 'info' | 'warning'color: string}interface AppState {// NavigationcurrentPage: NavPagesidebarCollapsed: booleancommandPaletteOpen: booleangodModeActive: boolean// Dataagents: Agent[]tasks: Task[]activity: ActivityItem[]metrics: {totalAgents: numbertasksCompleted: numbertimeSaved: numbersuccessRate: number}systemResources: {cpu: numbermemory: numberstorage: numbernetwork: number}// ActionssetCurrentPage: (page: NavPage) => voidtoggleSidebar: () => voidsetCommandPaletteOpen: (open: boolean) => voidtoggleGodMode: () => voidupdateSystemResources: (resources: Partial<AppState['systemResources']>) => void}export const AGENTS: Agent[] = [{ id: '1', name: 'Research Agent', role: 'Web Intelligence', status: 'active', color: '#6366f1', icon: '🔬', tasks: 47, efficiency: 92, uptime: 99.8, lastAction: 'Completed market research analysis', lastActionTime: '2m ago' },{ id: '2', name: 'Data Agent', role: 'Data Processing', status: 'active', color: '#22d3ee', icon: '📊', tasks: 83, efficiency: 98, uptime: 99.5, lastAction: 'Processed 1.2M data points', lastActionTime: '12m ago' },{ id: '3', name: 'Content Agent', role: 'Content Generation', status: 'active', color: '#a78bfa', icon: '✍️', tasks: 31, efficiency: 95, uptime: 98.2, lastAction: 'Generated blog draft', lastActionTime: '25m ago' },{ id: '4', name: 'Code Agent', role: 'Software Development', status: 'active', color: '#34d399', icon: '💻', tasks: 62, efficiency: 99, uptime: 99.9, lastAction: 'Deployed production API', lastActionTime: '1h ago' },{ id: '5', name: 'Design Agent', role: 'UI/UX Design', status: 'active', color: '#f472b6', icon: '🎨', tasks: 24, efficiency: 90, uptime: 97.8, lastAction: 'Created UI/UX mockups', lastActionTime: '2h ago' },{ id: '6', name: 'Workflow Agent', role: 'Automation', status: 'processing', color: '#fb923c', icon: '⚙️', tasks: 19, efficiency: 93, uptime: 98.1, lastAction: 'Running automation pipeline', lastActionTime: 'now' },{ id: '7', name: 'Memory Agent', role: 'Knowledge Storage', status: 'idle', color: '#fbbf24', icon: '🧠', tasks: 156, efficiency: 97, uptime: 99.9, lastAction: 'Indexed 4,200 documents', lastActionTime: '3h ago' },{ id: '8', name: 'Deploy Agent', role: 'Cloud Deployment', status: 'idle', color: '#f87171', icon: '🚀', tasks: 12, efficiency: 100, uptime: 99.7, lastAction: 'Deployed to Vercel', lastActionTime: '5h ago' },]export const ACTIVITY: ActivityItem[] = [{ id: '1', agent: 'Research Agent', action: 'Completed market research analysis', time: '2m ago', type: 'success', color: '#6366f1' },{ id: '2', agent: 'Data Agent', action: 'Processed 1.2M data points', time: '12m ago', type: 'processing', color: '#22d3ee' },{ id: '3', agent: 'Content Agent', action: 'Generated blog draft', time: '25m ago', type: 'success', color: '#a78bfa' },{ id: '4', agent: 'Code Agent', action: 'Deployed production API', time: '1h ago', type: 'success', color: '#34d399' },{ id: '5', agent: 'Design Agent', action: 'Created UI/UX mockups', time: '2h ago', type: 'info', color: '#f472b6' },{ id: '6', agent: 'Workflow Agent', action: 'Initiated automation pipeline', time: '3h ago', type: 'processing', color: '#fb923c' },]export const TASKS: Task[] = [{ id: 't1', title: 'Analyze competitor pricing strategy', status: 'completed', agent: 'Research Agent', progress: 100, createdAt: '2h ago', completedAt: '2m ago' },{ id: 't2', title: 'Generate Q4 performance report', status: 'running', agent: 'Data Agent', progress: 67, createdAt: '30m ago' },{ id: 't3', title: 'Refactor authentication module', status: 'running', agent: 'Code Agent', progress: 45, createdAt: '1h ago' },{ id: 't4', title: 'Create landing page copy', status: 'pending', agent: 'Content Agent', progress: 0, createdAt: '5m ago' },{ id: 't5', title: 'Design system components v2', status: 'pending', agent: 'Design Agent', progress: 0, createdAt: '10m ago' },{ id: 't6', title: 'Set up CI/CD pipeline', status: 'completed', agent: 'Deploy Agent', progress: 100, createdAt: '5h ago', completedAt: '4h ago' },]export const useAppStore = create<AppState>()(persist((set) => ({currentPage: 'dashboard',sidebarCollapsed: false,commandPaletteOpen: false,godModeActive: true,agents: AGENTS,tasks: TASKS,activity: ACTIVITY,metrics: {totalAgents: 12,tasksCompleted: 247,timeSaved: 128,successRate: 98.6,},systemResources: {cpu: 32,memory: 68,storage: 54,network: 29,},setCurrentPage: (page) => set({ currentPage: page }),toggleSidebar: () => set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed })),setCommandPaletteOpen: (open) => set({ commandPaletteOpen: open }),toggleGodMode: () => set((state) => ({ godModeActive: !state.godModeActive })),updateSystemResources: (resources) =>set((state) => ({ systemResources: { ...state.systemResources, ...resources } })),}),{ name: 'god-agent-os-store', partialize: (s) => ({ sidebarCollapsed: s.sidebarCollapsed, godModeActive: s.godModeActive }) }))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { create } from 'zustand'export type Page =| 'dashboard'| 'spaces'| 'agents'| 'tasks'| 'memory'| 'knowledge'| 'workflows'| 'analytics'| 'settings'| 'connectors'export type Space = 'core' | 'browser' | 'sandbox' | 'coding' | 'vision' | 'debug' | 'deploy' | 'communication'export type Role = 'cognition' | 'automation' | 'execution' | 'repair' | 'visual_intelligence'export interface SpaceStatus {name: Spaceactive: booleantaskCount: numberlastActive: number | nullcolor: stringicon: string}interface AppState {currentPage: PageactiveSpace: Space | nullcurrentRole: RolesidebarOpen: booleanspaces: Record<Space, SpaceStatus>setCurrentPage: (page: Page) => voidsetActiveSpace: (space: Space | null) => voidsetCurrentRole: (role: Role) => voidsetSidebarOpen: (open: boolean) => voidactivateSpace: (space: Space, role?: Role) => voiddeactivateSpace: (space: Space) => void}const initialSpaces: Record<Space, SpaceStatus> = {core: { name: 'core', active: false, taskCount: 0, lastActive: null, color: '#7c3aed', icon: '🧠' },browser: { name: 'browser', active: false, taskCount: 0, lastActive: null, color: '#2563eb', icon: '🌐' },sandbox: { name: 'sandbox', active: false, taskCount: 0, lastActive: null, color: '#059669', icon: '💻' },coding: { name: 'coding', active: false, taskCount: 0, lastActive: null, color: '#d97706', icon: '🔧' },vision: { name: 'vision', active: false, taskCount: 0, lastActive: null, color: '#db2777', icon: '👁️' },debug: { name: 'debug', active: false, taskCount: 0, lastActive: null, color: '#dc2626', icon: '🐛' },deploy: { name: 'deploy', active: false, taskCount: 0, lastActive: null, color: '#0891b2', icon: '🚀' },communication: { name: 'communication', active: false, taskCount: 0, lastActive: null, color: '#7c3aed', icon: '💬' },}export const useAppStore = create<AppState>((set) => ({currentPage: 'dashboard',activeSpace: null,currentRole: 'cognition',sidebarOpen: true,spaces: initialSpaces,setCurrentPage: (page) => set({ currentPage: page }),setActiveSpace: (space) => set({ activeSpace: space }),setCurrentRole: (role) => set({ currentRole: role }),setSidebarOpen: (open) => set({ sidebarOpen: open }),activateSpace: (space, role = 'cognition') => set((state) => ({activeSpace: space,currentRole: role,spaces: {...state.spaces,[space]: {...state.spaces[space],active: true,lastActive: Date.now(),taskCount: state.spaces[space].taskCount + 1,}}})),deactivateSpace: (space) => set((state) => ({spaces: {...state.spaces,[space]: { ...state.spaces[space], active: false }}})),}))
1234567891011121314151617181920{"buildCommand": "npm run build","outputDirectory": ".next","installCommand": "npm install","framework": "nextjs","env": {"NEXT_PUBLIC_API_URL": "https://PYAE1994-autonomous-coding-system.hf.space","NEXT_PUBLIC_APP_VERSION": "8.0.0","NEXT_PUBLIC_APP_NAME": "GOD AGENT OS"},"headers": [{"source": "/(.*)","headers": [{ "key": "X-Content-Type-Options", "value": "nosniff" },{ "key": "X-Frame-Options", "value": "SAMEORIGIN" },{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }]}]1234567891011121314151617181920212223{"buildCommand": "npm run build","outputDirectory": ".next","framework": "nextjs","rewrites": [{"source": "/api/v1/:path*","destination": "https://pyae1994-autonomous-coding-system.hf.space/api/v1/:path*"},{"source": "/ws/:path*","destination": "https://pyae1994-autonomous-coding-system.hf.space/ws/:path*"}],"headers": [{"source": "/(.*)","headers": [{ "key": "X-Powered-By", "value": "Pyae Sone" },{ "key": "X-Frame-Options", "value": "SAMEORIGIN" }]}]
.github/workflows/deploy.yml+41-111
backend/Dockerfile.hf+14-23
backend/README.md+34-43
backend/api/routes/health.py+8-2
backend/kernel/__init__.pyAdded+1
backend/kernel/agent_kernel.pyAdded+331
backend/main_v9.pyAdded+430
backend/spaces/__init__.pyAdded+21
backend/spaces/base_space.pyAdded+91
backend/spaces/browser_space.pyAdded+104
backend/spaces/coding_space.pyAdded+106
backend/spaces/communication_space.pyAdded+106
backend/spaces/core_space.pyAdded+48
backend/spaces/debug_space.pyAdded+120
backend/spaces/deploy_space.pyAdded+109
backend/spaces/sandbox_space.pyAdded+178
backend/spaces/vision_space.pyAdded+80
frontend/app/layout.tsx+2-2
frontend/app/page.tsx+59-11
frontend/components/chat/ChatPanel.tsx+8-1
frontend/components/dashboard/ActivityFeed.tsx+1-1
frontend/components/dashboard/AgentFleetCard.tsx+1-1
frontend/components/dashboard/GodModeCard.tsx+2-1
frontend/components/dashboard/SystemResources.tsx+1-1
frontend/components/pages/AgentsPage.tsx+11-1
frontend/components/pages/ConnectorsPage.tsxAdded+224
frontend/components/pages/DashboardPage.tsx+423-88
frontend/components/pages/SpacesPage.tsxAdded+267
frontend/components/pages/TasksPage.tsx+2-1
frontend/components/shared/Sidebar.tsx+100-120
frontend/components/shared/TopBar.tsx+76-163
frontend/lib/api.ts+27-134
frontend/next.config.js+21-8
frontend/package-lock.json+4-4
frontend/store/useAppStore.ts+70-117
frontend/vercel.json+12-9