diff --git a/.github/workflows/generator-generic-ossf-slsa3-publish.yml b/.github/workflows/generator-generic-ossf-slsa3-publish.yml new file mode 100644 index 0000000..35c829b --- /dev/null +++ b/.github/workflows/generator-generic-ossf-slsa3-publish.yml @@ -0,0 +1,66 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +# This workflow lets you generate SLSA provenance file for your project. +# The generation satisfies level 3 for the provenance requirements - see https://slsa.dev/spec/v0.1/requirements +# The project is an initiative of the OpenSSF (openssf.org) and is developed at +# https://github.com/slsa-framework/slsa-github-generator. +# The provenance file can be verified using https://github.com/slsa-framework/slsa-verifier. +# For more information about SLSA and how it improves the supply-chain, visit slsa.dev. + +name: SLSA generic generator +on: + workflow_dispatch: + release: + types: [created] + +jobs: + build: + runs-on: ubuntu-latest + outputs: + digests: ${{ steps.hash.outputs.digests }} + + steps: + - uses: actions/checkout@v4 + + # ======================================================== + # + # Step 1: Build your artifacts. + # + # ======================================================== + - name: Build artifacts + run: | + # These are some amazing artifacts. + echo "artifact1" > artifact1 + echo "artifact2" > artifact2 + + # ======================================================== + # + # Step 2: Add a step to generate the provenance subjects + # as shown below. Update the sha256 sum arguments + # to include all binaries that you generate + # provenance for. + # + # ======================================================== + - name: Generate subject for provenance + id: hash + run: | + set -euo pipefail + + # List the artifacts the provenance will refer to. + files=$(ls artifact*) + # Generate the subjects (base64 encoded). + echo "hashes=$(sha256sum $files | base64 -w0)" >> "${GITHUB_OUTPUT}" + + provenance: + needs: [build] + permissions: + actions: read # To read the workflow path. + id-token: write # To sign the provenance. + contents: write # To add assets to a release. + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.4.0 + with: + base64-subjects: "${{ needs.build.outputs.digests }}" + upload-assets: true # Optional: Upload to a new release diff --git a/.github/workflows/webpack.yml b/.github/workflows/webpack.yml new file mode 100644 index 0000000..9626ff6 --- /dev/null +++ b/.github/workflows/webpack.yml @@ -0,0 +1,28 @@ +name: NodeJS with Webpack + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x, 22.x] + + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Build + run: | + npm install + npx webpack diff --git a/.gitignore b/.gitignore index d5a18de..23e2e7c 100644 --- a/.gitignore +++ b/.gitignore @@ -427,3 +427,6 @@ FodyWeavers.xsd *.msix *.msm *.msp + +# Static build output +dist/ diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..c4d9416 --- /dev/null +++ b/.npmrc @@ -0,0 +1,5 @@ +shamefully-hoist=true +strict-peer-dependencies=false +public-hoist-pattern[]=*eslint* +public-hoist-pattern[]=*prettier* +public-hoist-pattern[]=*typescript* diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..da0ffa2 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,379 @@ +# πŸ—οΈ AI Agent Build System - Architecture Documentation + +## Table of Contents +1. [System Overview](#system-overview) +2. [Monorepo Structure](#monorepo-structure) +3. [Service Architecture](#service-architecture) +4. [Data Flow](#data-flow) +5. [Technology Stack](#technology-stack) +6. [Integration Points](#integration-points) +7. [Deployment](#deployment) + +--- + +## System Overview + +The AI Agent Build System is a **monorepo-based platform** that integrates: +- **CodeXPR** (AI Code Explorer UI) +- **Sandbox-Ai** (CLI Agent Builder) +- **Unified Dashboard** (Chat + Tasks + Agent Management) +- **API Gateway** (Service Orchestration) + +### Key Principles +- βœ… Type-safe across all services +- βœ… Real-time communication via WebSocket +- βœ… Scalable microservices architecture +- βœ… Shared business logic and types +- βœ… Independent deployment capability + +--- + +## Monorepo Structure + +``` +ai-agent-build-system/ +β”œβ”€β”€ apps/ # Frontend applications +β”‚ β”œβ”€β”€ web/ # Main React dashboard (port 3000) +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ components/ # Reusable React components +β”‚ β”‚ β”‚ β”œβ”€β”€ pages/ # Route pages (Chat, Tasks, Agent) +β”‚ β”‚ β”‚ β”œβ”€β”€ hooks/ # Custom React hooks +β”‚ β”‚ β”‚ β”œβ”€β”€ stores/ # Zustand state management +β”‚ β”‚ β”‚ β”œβ”€β”€ services/ # API client services +β”‚ β”‚ β”‚ β”œβ”€β”€ App.tsx # Main router +β”‚ β”‚ β”‚ β”œβ”€β”€ main.tsx # Entry point +β”‚ β”‚ β”‚ └── index.css # Global styles +β”‚ β”‚ β”œβ”€β”€ vite.config.ts # Vite bundler config +β”‚ β”‚ β”œβ”€β”€ tsconfig.json +β”‚ β”‚ └── package.json +β”‚ └── sandbox-ai/ # Sandbox CLI app (future) +β”‚ +β”œβ”€β”€ services/ # Microservices +β”‚ β”œβ”€β”€ api-gateway/ # Main API Gateway (port 3001) +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts # Express server setup +β”‚ β”‚ β”‚ β”œβ”€β”€ routes/ # API route definitions +β”‚ β”‚ β”‚ β”œβ”€β”€ middleware/ # Auth, logging, etc. +β”‚ β”‚ β”‚ β”œβ”€β”€ websocket/ # WebSocket handlers +β”‚ β”‚ β”‚ └── utils/ # Helper functions +β”‚ β”‚ β”œβ”€β”€ tsconfig.json +β”‚ β”‚ └── package.json +β”‚ β”œβ”€β”€ api-server/ # Chat & Task service (port 3002) +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ routes/ +β”‚ β”‚ β”‚ β”œβ”€β”€ db/ # Drizzle ORM setup +β”‚ β”‚ β”‚ └── services/ +β”‚ β”‚ └── package.json +β”‚ └── agent-service/ # Agent orchestration (port 3003) +β”‚ β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ package.json +β”‚ +β”œβ”€β”€ packages/ # Shared packages +β”‚ β”œβ”€β”€ types/ # TypeScript interfaces & types +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts # Main exports +β”‚ β”‚ β”‚ β”œβ”€β”€ api.ts # API types +β”‚ β”‚ β”‚ β”œβ”€β”€ domain.ts # Domain models +β”‚ β”‚ β”‚ └── events.ts # Event types +β”‚ β”‚ β”œβ”€β”€ tsconfig.json +β”‚ β”‚ └── package.json +β”‚ β”œβ”€β”€ utils/ # Utility functions +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ helpers.ts # General helpers +β”‚ β”‚ β”‚ β”œβ”€β”€ validators.ts # Input validation +β”‚ β”‚ β”‚ └── formatters.ts # Data formatting +β”‚ β”‚ └── package.json +β”‚ └── shared/ # Shared exports +β”‚ β”œβ”€β”€ src/index.ts +β”‚ └── package.json +β”‚ +β”œβ”€β”€ docker-compose.yml # Local dev environment +β”œβ”€β”€ .env.example # Environment template +β”œβ”€β”€ pnpm-workspace.yaml # Workspace configuration +β”œβ”€β”€ turbo.json # Turbo build config +β”œβ”€β”€ tsconfig.json # Root TypeScript config +β”œβ”€β”€ package.json # Root package.json +β”œβ”€β”€ ARCHITECTURE.md # This file +β”œβ”€β”€ IMPLEMENTATION.md # Step-by-step setup guide +└── README.md # Quick start guide +``` + +--- + +## Service Architecture + +### 1. Frontend Layer (React App) + +**Port:** 3000 +**Purpose:** User interface for chat, task management, and agent configuration + +**Key Features:** +- Real-time chat interface +- Task dashboard with status tracking +- Agent builder and configuration UI +- Session history sidebar +- Dark theme with Tailwind CSS + +**Technologies:** +- React 18 with TypeScript +- Vite for bundling +- Zustand for state management +- Framer Motion for animations +- Axios for API calls +- WebSocket for real-time updates + +### 2. API Gateway + +**Port:** 3001 +**Purpose:** Central routing and orchestration of all backend services + +**Responsibilities:** +- Route requests to appropriate microservices +- Handle WebSocket connections +- Authentication & authorization +- Request/response transformation +- Rate limiting and caching +- Logging and monitoring + +**Routes:** +``` +GET /health β†’ Health check +GET /api/chat/* β†’ Chat service +GET /api/tasks/* β†’ Task service +GET /api/agent/* β†’ Agent service +GET /api/repos/* β†’ Repository service +WS ws://*/socket β†’ WebSocket endpoint +``` + +### 3. Chat & Task Service + +**Port:** 3002 +**Purpose:** Manage chat conversations and tasks + +**Endpoints:** +``` +POST /chats β†’ Create chat +GET /chats β†’ List chats +GET /chats/:id β†’ Get chat details +PUT /chats/:id β†’ Update chat +DELETE /chats/:id β†’ Delete chat + +POST /messages β†’ Create message +GET /messages/:chatId β†’ Get chat messages + +POST /tasks β†’ Create task +GET /tasks β†’ List tasks +GET /tasks/:id β†’ Get task details +PUT /tasks/:id β†’ Update task +DELETE /tasks/:id β†’ Delete task +``` + +### 4. Agent Service + +**Port:** 3003 +**Purpose:** Orchestrate AI agents and automation workflows + +**Responsibilities:** +- Agent lifecycle management +- Workflow execution +- Tool integration (GitHub, OpenAI, etc.) +- Event handling and callbacks +- Result processing and storage + +### 5. Database Layer + +**PostgreSQL (Port 5432)** +- Main data store +- Schema managed by Drizzle ORM +- Tables: users, chats, messages, tasks, agents, sessions + +**Redis (Port 6379)** +- Session cache +- Real-time state synchronization +- Message queue for async jobs +- WebSocket connection management + +--- + +## Data Flow + +### User Chat Interaction + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ React App β”‚ +β”‚ (Port 3000)β”‚ +β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ + β”‚ WebSocket + β”‚ JSON payload + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ API Gateway β”‚ +β”‚ (Port 3001) β”‚ +β”‚ β”œβ”€ Validate input β”‚ +β”‚ β”œβ”€ Authenticate user β”‚ +β”‚ └─ Route to service β”‚ +β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ HTTP/gRPC + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Chat Service β”‚ +β”‚ (Port 3002) β”‚ +β”‚ β”œβ”€ Store message β”‚ +β”‚ β”œβ”€ Call AI API (OpenAI) β”‚ +β”‚ └─ Generate response β”‚ +β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”œβ”€β†’ PostgreSQL (Store) + β”œβ”€β†’ Redis (Cache) + └─→ WebSocket (Broadcast) + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ React App β”‚ +β”‚ Receives update β”‚ +β”‚ Rerender UI β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Task Execution Flow + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User Creates β”‚ +β”‚ Task (React) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ API Gateway β”‚ +β”‚ POST /api/tasks β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Task Service β”‚ +β”‚ 1. Create record β”‚ +β”‚ 2. Set status:queued +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”œβ†’ PostgreSQL + β”œβ†’ Redis queue + β””β†’ Emit event + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Agent Service β”‚ +β”‚ Picks up task β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”œβ”€β†’ 1. Analyze + β”œβ”€β†’ 2. Plan + β”œβ”€β†’ 3. Execute + β”œβ”€β†’ 4. Verify + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Update task β”‚ +β”‚ status:completedβ”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”œβ†’ PostgreSQL + β”œβ†’ Notify user + β””β†’ WebSocket update +``` + +--- + +## Technology Stack + +### Frontend +- **React 18** - UI framework +- **TypeScript 5.9** - Type safety +- **Vite 5** - Module bundler +- **Zustand** - State management +- **Framer Motion** - Animations +- **Tailwind CSS** - Styling +- **Axios** - HTTP client +- **WebSocket** - Real-time communication + +### Backend +- **Node.js 18+** - Runtime +- **Express 5** - Web framework +- **TypeScript** - Type safety +- **PostgreSQL** - Primary database +- **Redis** - Cache & queue +- **Drizzle ORM** - Database abstraction +- **Pino** - Logging +- **Zod** - Input validation + +### Monorepo & Build +- **pnpm** - Package manager +- **Turbo** - Build orchestration +- **esbuild** - JavaScript bundler +- **ts-node** - TypeScript execution + +### DevOps +- **Docker** - Containerization +- **Docker Compose** - Orchestration +- **GitHub Actions** - CI/CD + +--- + +## Integration Points + +### CodeXPR Integration +- UI components from CodeXPR merged into unified dashboard +- Chat interface reused +- Task management system inherited +- GitHub integration maintained + +### Sandbox-Ai Integration +- CLI commands available via web UI +- Agent execution engine integrated +- Session history sync'd +- Real-time output streaming + +### External APIs +- **OpenAI API** - AI chat and code generation +- **GitHub API** - Repository operations +- **Authentication Providers** - Google OAuth, GitHub OAuth + +--- + +## Deployment + +### Local Development +```bash +pnpm install +pnpm dev +``` + +### Docker Compose (Recommended) +```bash +pnpm docker:build +pnpm docker:up +``` + +### Production +```bash +pnpm build +DOCKER_BUILDKIT=1 docker build -t ai-agent-build . +docker run -d -p 80:3000 ai-agent-build +``` + +### Environment Configuration +See `.env.example` for all required variables. + +--- + +## Next Steps + +1. Install dependencies: `pnpm install` +2. Setup database: `pnpm db:migrate` +3. Start development: `pnpm dev` +4. Open browser: http://localhost:3000 + +For detailed implementation guide, see [IMPLEMENTATION.md](./IMPLEMENTATION.md) diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md new file mode 100644 index 0000000..bad0f86 --- /dev/null +++ b/IMPLEMENTATION.md @@ -0,0 +1,840 @@ +# πŸ“‹ AI Agent Build System - Implementation Guide + +## Phase-by-Phase Development Guide + +This document provides a complete, step-by-step guide to build, maintain, and extend the integrated AI Agent Build System from zero to production. + +### Table of Contents +1. [Phase 0: Prerequisites & Setup](#phase-0-prerequisites--setup) +2. [Phase 1: Environment Configuration](#phase-1-environment-configuration) +3. [Phase 2: Database Setup](#phase-2-database-setup) +4. [Phase 3: Backend Development](#phase-3-backend-development) +5. [Phase 4: Frontend Development](#phase-4-frontend-development) +6. [Phase 5: Integration & Testing](#phase-5-integration--testing) +7. [Phase 6: Deployment](#phase-6-deployment) +8. [Maintenance & Troubleshooting](#maintenance--troubleshooting) +9. [Common Workflows](#common-workflows) + +--- + +## Phase 0: Prerequisites & Setup + +### Step 0.1: System Requirements + +```bash +# Check Node.js version (>= 18.0.0) +node --version +# Expected: v18.x.x or higher + +# Check npm version +npm --version +# Expected: 9.x.x or higher + +# Install pnpm globally +npm install -g pnpm@latest + +# Verify pnpm +pnpm --version +# Expected: 8.x.x or higher +``` + +**Required Software:** +- Node.js 18+ (https://nodejs.org/) +- pnpm 8+ (https://pnpm.io/) +- Docker & Docker Compose (https://www.docker.com/) +- Git (https://git-scm.com/) + +### Step 0.2: Clone & Navigate + +```bash +# Clone the repository +git clone https://github.com/HuynhThuong0711/CodeXPR.git +cd CodeXPR + +# Checkout the integrated-system branch +git checkout feat/integrated-system + +# Verify you're on the right branch +git branch +# Output: * feat/integrated-system +# main + +# View the new structure +ls -la +``` + +### Step 0.3: Initial Project Structure Check + +```bash +# Verify all key directories exist +test -d packages/types && echo "βœ“ packages/types" || echo "βœ— packages/types missing" +test -d packages/utils && echo "βœ“ packages/utils" || echo "βœ— packages/utils missing" +test -d apps/web && echo "βœ“ apps/web" || echo "βœ— apps/web missing" +test -d services/api-gateway && echo "βœ“ services/api-gateway" || echo "βœ— services/api-gateway missing" +test -f pnpm-workspace.yaml && echo "βœ“ pnpm-workspace.yaml" || echo "βœ— pnpm-workspace.yaml missing" +test -f docker-compose.yml && echo "βœ“ docker-compose.yml" || echo "βœ— docker-compose.yml missing" +``` + +--- + +## Phase 1: Environment Configuration + +### Step 1.1: Copy Environment Template + +```bash +# Copy the example environment file +cp .env.example .env + +# List what was created +ls -la | grep env +``` + +### Step 1.2: Configure Local Development Variables + +Edit `.env` file: + +```bash +nano .env +# Or use your editor: code .env, vim .env, etc. +``` + +Required configurations: + +```bash +# Database +DATABASE_URL="postgresql://ai-agent:dev-password@localhost:5432/ai_agent_db" +REDIS_URL="redis://localhost:6379" + +# API Server +API_PORT=3001 +API_HOST=0.0.0.0 +NODE_ENV=development +LOG_LEVEL=debug + +# Web App +VITE_API_URL=http://localhost:3001 +VITE_WS_URL=ws://localhost:3001 +VITE_APP_ENV=development + +# GitHub (Get from https://github.com/settings/tokens) +VITE_GITHUB_TOKEN=ghp_xxxxxxxxxxxxx +VITE_GITHUB_API_URL=https://api.github.com + +# OpenAI (Get from https://platform.openai.com/api-keys) +VITE_OPENAI_API_KEY=sk-xxxxxxxxxxxxx +VITE_OPENAI_MODEL=gpt-4o + +# Authentication +AUTH_SECRET=your_random_secret_string_here +GOOGLE_CLIENT_ID=xxxx.apps.googleusercontent.com +GOOGLE_CLIENT_SECRET=your_secret_here +GITHUB_CLIENT_ID=your_github_app_id +GITHUB_CLIENT_SECRET=your_github_secret +``` + +### Step 1.3: Verify Configuration + +```bash +# Check that .env file is readable +cat .env | head -20 + +# Verify it's not committed (should be in .gitignore) +git status | grep .env +# Should NOT show .env as tracked + +# Make sure it's in gitignore +echo ".env" >> .gitignore +echo ".env.local" >> .gitignore +``` + +--- + +## Phase 2: Database Setup + +### Step 2.1: Start Database Services + +**Option A: Using Docker (Recommended)** + +```bash +# Build Docker images +pnpm docker:build + +# Start services +pnpm docker:up + +# Verify services are running +docker ps +# Should see: postgres, redis, api-server, web containers running + +# Check PostgreSQL is ready +pnpm docker:logs postgres +# Look for: "database system is ready to accept connections" +``` + +**Option B: Manual Setup** + +```bash +# Install PostgreSQL 16 (macOS example with Homebrew) +brew install postgresql@16 +brew services start postgresql@16 + +# Install Redis +brew install redis +brew services start redis + +# Verify PostgreSQL +psql --version +# Expected: psql (PostgreSQL) 16.x + +# Create database +psql -U postgres -c "CREATE DATABASE ai_agent_db;" +psql -U postgres -c "CREATE USER 'ai-agent' WITH PASSWORD 'dev-password';" +psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE ai_agent_db TO 'ai-agent';" + +# Verify connection +psql -U ai-agent -d ai_agent_db -c "SELECT 1;" +``` + +### Step 2.2: Install Dependencies + +```bash +# Clear any existing node_modules +rm -rf node_modules +rm -rf pnpm-lock.yaml + +# Install all workspace dependencies +pnpm install + +# This will: +# βœ“ Download packages from npm +# βœ“ Link workspace packages +# βœ“ Setup symlinks +# βœ“ Install peer dependencies + +# Verify installation +pnpm list --depth=0 +``` + +### Step 2.3: Database Migration (If Applicable) + +```bash +# When you add database schemas, run migrations +# pnpm --filter @ai-agent/api-server run db:migrate + +# For now, just verify connection +pnpm db:check 2>/dev/null || echo "DB schema check skipped (schema not yet created)" +``` + +--- + +## Phase 3: Backend Development + +### Step 3.1: Understanding the API Gateway + +The API Gateway (port 3001) is the main entry point: + +```bash +# Structure +services/api-gateway/ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ index.ts # Express server & WebSocket setup +β”‚ β”œβ”€β”€ routes/ # API route handlers +β”‚ β”œβ”€β”€ middleware/ # Auth, logging, error handling +β”‚ └── websocket/ # Real-time communication +β”œβ”€β”€ package.json +└── tsconfig.json +``` + +### Step 3.2: Start API Gateway in Development + +```bash +# Terminal 1: Start API Gateway +pnpm dev:api + +# Expected output: +# > @ai-agent/api-gateway dev +# πŸš€ API Gateway running on port 3001 +# WebSocket server ready at ws://localhost:3001 + +# In Terminal 2: Test the gateway +curl http://localhost:3001/health +# Expected response: +# {"status":"ok","timestamp":"2024-01-20T12:00:00.000Z"} +``` + +### Step 3.3: Understanding Backend Services + +Each service has its own responsibility: + +**API Gateway (Port 3001)** +- Routes requests to appropriate services +- Handles WebSocket connections +- Authentication & authorization + +**Chat & Task Service (Port 3002) - Create Later** +```bash +# Services to create: +# POST /api/chat/create β†’ Create new chat +# GET /api/chat/list β†’ List chats +# POST /api/task/create β†’ Create task +# GET /api/task/list β†’ List tasks +``` + +### Step 3.4: Developing New Endpoints + +When adding new endpoints: + +```typescript +// services/api-gateway/src/routes/example.ts +import { Router } from 'express'; + +const router = Router(); + +// GET /api/example +router.get('/', (req, res) => { + res.json({ message: 'Example endpoint' }); +}); + +// POST /api/example +router.post('/', (req, res) => { + const { data } = req.body; + // Process data + res.json({ success: true, data }); +}); + +export default router; +``` + +Then register in `src/index.ts`: + +```typescript +import exampleRouter from './routes/example'; +app.use('/api/example', exampleRouter); +``` + +--- + +## Phase 4: Frontend Development + +### Step 4.1: Start Web Application + +```bash +# Terminal 1: Already running API Gateway +pnpm dev:api + +# Terminal 2: Start React web app +pnpm dev:ui + +# Expected output: +# > @ai-agent/web dev +# VITE v5.0.8 ready in xxx ms +# ➜ Local: http://localhost:3000 +# ➜ press h to show help +``` + +### Step 4.2: Access the Application + +```bash +# Open in browser +open http://localhost:3000 + +# Or manually: +# - Chrome: http://localhost:3000 +# - Firefox: http://localhost:3000 +# - Safari: http://localhost:3000 + +# Expected to see: +# βœ“ Logo and title: "πŸ€– AI Agent Builder" +# βœ“ Navigation menu: Chat, Tasks, Agent +# βœ“ Dark theme (background: #0d0f14) +``` + +### Step 4.3: Frontend Structure + +```bash +apps/web/src/ +β”œβ”€β”€ components/ # Reusable components +β”‚ β”œβ”€β”€ Layout.tsx # Main layout +β”‚ β”œβ”€β”€ Header.tsx # Header component +β”‚ └── ... +β”œβ”€β”€ pages/ # Page components +β”‚ β”œβ”€β”€ ChatView.tsx # Chat page +β”‚ β”œβ”€β”€ TasksView.tsx # Tasks page +β”‚ └── AgentView.tsx # Agent page +β”œβ”€β”€ hooks/ # Custom React hooks +β”‚ β”œβ”€β”€ useApi.ts # API calls +β”‚ β”œβ”€β”€ useWebSocket.ts # WebSocket communication +β”‚ └── ... +β”œβ”€β”€ stores/ # Zustand state +β”‚ β”œβ”€β”€ chatStore.ts # Chat state +β”‚ β”œβ”€β”€ taskStore.ts # Task state +β”‚ └── ... +β”œβ”€β”€ services/ # API client +β”‚ β”œβ”€β”€ api.ts # Axios instance +β”‚ β”œβ”€β”€ chatService.ts # Chat API calls +β”‚ └── ... +β”œβ”€β”€ App.tsx # Main router +└── main.tsx # Entry point +``` + +### Step 4.4: Adding a New Component + +```typescript +// apps/web/src/components/ChatMessage.tsx +import { motion } from 'framer-motion'; +import type { Message } from '@ai-agent/types'; + +interface ChatMessageProps { + message: Message; +} + +export function ChatMessage({ message }: ChatMessageProps) { + return ( + +

{message.content}

+ {new Date(message.createdAt).toLocaleTimeString()} +
+ ); +} +``` + +### Step 4.5: Styling with Tailwind + +The app uses Tailwind CSS for styling: + +```html + + +``` + +--- + +## Phase 5: Integration & Testing + +### Step 5.1: Full Stack Development + +Run all services together: + +```bash +# Terminal 1: Database + Redis +pnpm docker:up + +# Terminal 2: API Gateway +pnpm dev:api + +# Terminal 3: Web App +pnpm dev:ui + +# All three running = full stack ready +# Access at: http://localhost:3000 +``` + +### Step 5.2: Testing API Endpoints + +```bash +# Install curl (usually pre-installed) +curl --version + +# Test health endpoint +curl http://localhost:3001/health + +# Test chat endpoint +curl -X GET http://localhost:3001/api/chat + +# Test with data (POST) +curl -X POST http://localhost:3001/api/chat/create \ + -H "Content-Type: application/json" \ + -d '{"title":"My first chat"}' + +# Test WebSocket connection +# Use a WebSocket client or browser console: +const ws = new WebSocket('ws://localhost:3001'); +ws.onopen = () => ws.send('Hello!'); +ws.onmessage = (e) => console.log(e.data); +``` + +### Step 5.3: Type Safety Checking + +```bash +# Check TypeScript compilation +pnpm typecheck + +# Expected output: +# βœ“ No TypeScript errors + +# If errors occur, fix them immediately: +pnpm typecheck 2>&1 | head -20 # See first 20 errors +``` + +### Step 5.4: Code Linting + +```bash +# Check code quality +pnpm lint + +# Format code automatically +pnpm format + +# Verify files are formatted +git diff --no-index /dev/null apps/web/src/App.tsx | head -5 +``` + +--- + +## Phase 6: Deployment + +### Step 6.1: Production Build + +```bash +# Build all apps +pnpm build + +# This runs: +# 1. typecheck - Ensure types are correct +# 2. build - Compile TypeScript to JavaScript +# 3. Optimize bundles + +# Check build output +ls -lah apps/web/dist/ +ls -lah services/api-gateway/dist/ +``` + +### Step 6.2: Docker Deployment + +```bash +# Build Docker image (production) +DOCKER_BUILDKIT=1 docker build -t ai-agent-build:latest . + +# Run container +docker run -d \ + --name ai-agent-prod \ + -p 80:3000 \ + -e NODE_ENV=production \ + -e DATABASE_URL="postgresql://..." \ + ai-agent-build:latest + +# Check logs +docker logs -f ai-agent-prod + +# Access at: http://localhost +``` + +### Step 6.3: Environment Variables for Production + +```bash +# Create production .env file +cat > .env.production << 'EOF' +NODE_ENV=production +DATABASE_URL=postgresql://user:pass@prod-db:5432/ai_agent_db +REDIS_URL=redis://prod-redis:6379 +API_PORT=3001 +VITE_API_URL=https://api.yourdomain.com +VITE_WS_URL=wss://api.yourdomain.com +AUTH_SECRET=your_production_secret +VITE_OPENAI_API_KEY=sk_prod_xxxxx +VITE_GITHUB_TOKEN=ghp_prod_xxxxx +EOF +``` + +### Step 6.4: Deploy to Cloud (Example: Heroku) + +```bash +# Install Heroku CLI +# https://devcenter.heroku.com/articles/heroku-cli + +# Login to Heroku +heroku login + +# Create app +heroku create ai-agent-builder + +# Set environment variables +heroku config:set NODE_ENV=production --app ai-agent-builder +heroku config:set DATABASE_URL=postgresql://... --app ai-agent-builder + +# Deploy +git push heroku feat/integrated-system:main + +# View logs +heroku logs --tail --app ai-agent-builder +``` + +--- + +## Maintenance & Troubleshooting + +### Common Issues & Solutions + +#### Issue 1: "Port 3000 already in use" + +```bash +# Find process using port 3000 +lsof -i :3000 + +# Kill the process +kill -9 + +# Or use different port +VITE_PORT=3001 pnpm dev:ui +``` + +#### Issue 2: "Cannot find module '@ai-agent/types'" + +```bash +# Reinstall dependencies +pnpm install + +# Clear cache +pnpm store prune + +# Verify symlinks +ls -la node_modules/@ai-agent/ +``` + +#### Issue 3: Database connection fails + +```bash +# Check if PostgreSQL is running +psql -U ai-agent -d ai_agent_db -c "SELECT 1;" + +# If not running, start it +brew services start postgresql@16 + +# Verify connection string in .env +echo $DATABASE_URL + +# Test with psql +psql $DATABASE_URL +``` + +#### Issue 4: WebSocket connection timeout + +```bash +# Check API Gateway is running +curl http://localhost:3001/health + +# Check WebSocket endpoint +# In browser console: +const ws = new WebSocket('ws://localhost:3001'); +console.log(ws.readyState); // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED + +# Restart API Gateway +kill %1 # Stop dev:api +pnpm dev:api # Restart +``` + +#### Issue 5: TypeScript errors on build + +```bash +# Check for type errors +pnpm typecheck 2>&1 + +# Fix with type annotations +# Add explicit types to functions: +function processData(input: string): string { + return input.toUpperCase(); +} + +# Not: +function processData(input) { // ❌ Missing type + return input.toUpperCase(); +} +``` + +### Regular Maintenance Tasks + +#### Weekly +```bash +# Update dependencies +pnpm update + +# Run tests +pnpm test + +# Check for security vulnerabilities +pnpm audit +``` + +#### Monthly +```bash +# Backup database +pg_dump ai_agent_db > backup_$(date +%Y%m%d).sql + +# Update Docker images +docker pull postgres:16 +docker pull redis:7 + +# Review logs for errors +pnpm docker:logs +``` + +#### Quarterly +```bash +# Audit code quality +pnpm lint + +# Type check everything +pnpm typecheck + +# Update major dependencies +pnpm update --interactive +``` + +--- + +## Common Workflows + +### Workflow 1: Add a New Feature + +```bash +# 1. Create feature branch +git checkout -b feature/add-notifications + +# 2. Update types if needed +# Edit: packages/types/src/index.ts +# Add new interfaces + +# 3. Create backend endpoint +# Create: services/api-gateway/src/routes/notifications.ts +# Register in: services/api-gateway/src/index.ts + +# 4. Build and test +pnpm dev:api +curl http://localhost:3001/api/notifications + +# 5. Create frontend component +# Create: apps/web/src/components/NotificationCenter.tsx + +# 6. Update types and test +pnpm dev:ui +# Test at http://localhost:3000 + +# 7. Commit and push +git add . +git commit -m "feat: add notification system" +git push origin feature/add-notifications + +# 8. Create pull request on GitHub +``` + +### Workflow 2: Debug Issue + +```bash +# 1. Identify the issue +echo "Describe what's broken" + +# 2. Start all services with logging +NODE_DEBUG=* pnpm dev:api & +pnpm dev:ui & +pnpm docker:logs + +# 3. Test the endpoint +curl -v http://localhost:3001/api/problematic-route + +# 4. Check browser console +# Press F12 β†’ Console β†’ Look for errors + +# 5. Add console logs +# Edit component/service and add: +console.log('Debug info:', variable); + +# 6. Fix the issue +# Edit the problematic file + +# 7. Verify fix +pnpm typecheck +pnpm lint + +# 8. Test thoroughly +curl http://localhost:3001/api/fixed-route +``` + +### Workflow 3: Prepare for Production Release + +```bash +# 1. Ensure all tests pass +pnpm test + +# 2. Type check +pnpm typecheck + +# 3. Lint +pnpm lint + +# 4. Format code +pnpm format + +# 5. Build +pnpm build + +# 6. Test production build locally +pnpm preview +# Test at http://localhost:4173 + +# 7. Update version +# Edit: package.json +# Change: "version": "1.0.1" + +# 8. Create changelog +echo "## v1.0.1 - $(date +%Y-%m-%d)" >> CHANGELOG.md +echo "- Fixed bug X" >> CHANGELOG.md +echo "- Added feature Y" >> CHANGELOG.md + +# 9. Commit and tag +git add . +git commit -m "chore: release v1.0.1" +git tag -a v1.0.1 -m "Release v1.0.1" + +# 10. Push to GitHub +git push origin feat/integrated-system +git push origin v1.0.1 +``` + +--- + +## Quick Reference + +### Essential Commands + +```bash +pnpm install # Install all dependencies +pnpm dev # Start all services +pnpm dev:ui # Start web app only +pnpm dev:api # Start API gateway only +pnpm build # Build for production +pnpm typecheck # Check TypeScript +pnpm lint # Check code quality +pnpm format # Auto-format code +pnpm docker:build # Build Docker images +pnpm docker:up # Start Docker services +pnpm docker:down # Stop Docker services +pnpm docker:logs # View Docker logs +``` + +### Useful URLs + +- **Web App:** http://localhost:3000 +- **API Gateway:** http://localhost:3001 +- **API Health:** http://localhost:3001/health +- **WebSocket:** ws://localhost:3001 +- **PostgreSQL:** localhost:5432 +- **Redis:** localhost:6379 + +### File Locations + +- **Environment:** `.env` (in project root) +- **Types:** `packages/types/src/index.ts` +- **API Gateway:** `services/api-gateway/src/index.ts` +- **Web App:** `apps/web/src/App.tsx` +- **Components:** `apps/web/src/components/` +- **State:** `apps/web/src/stores/` + +--- + +For more details, see [ARCHITECTURE.md](./ARCHITECTURE.md) and [README.md](./README.md) diff --git a/README.md b/README.md index 81fa532..cc82ee2 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,815 @@ -# CodeXPR -Frontend (Next.js + React) - β”‚ - β–Ό -Backend (Node.js/Fastify) - β”‚ - β”œβ”€β”€ OpenAI Responses API - β”œβ”€β”€ GitHub App - β”œβ”€β”€ Task Queue (BullMQ) - β”œβ”€β”€ PostgreSQL - β”œβ”€β”€ Redis - └── Sandbox (Docker / Firecracker) - β”‚ - β–Ό - Clone Repository - Install - Edit code - Run tests - Commit - Push branch - Create Pull Request - -Chα»©c nΔƒng chΓ­nh -πŸ€– Chat vα»›i AI. -πŸ“‚ KαΊΏt nα»‘i GitHub. -🌿 Tα»± tαΊ‘o branch. -πŸ“ AI đọc toΓ n bα»™ repository. -πŸ”§ ViαΊΏt vΓ  sα»­a code. -πŸ§ͺ ChαΊ‘y build, lint, test. -πŸ“Š Hiển thα»‹ log thời gian thα»±c. -πŸ“„ TαΊ‘o Pull Request. -πŸ”„ ChαΊ‘y nhiều task song song. -πŸ’¬ LΖ°u lα»‹ch sα»­ hα»™i thoαΊ‘i. -CΓ΄ng nghệ -Frontend: Next.js 15, React, Tailwind CSS, shadcn/ui. -Backend: Node.js, Fastify. -Database: PostgreSQL. -Cache/Queue: Redis + BullMQ. -Sandbox: Docker hoαΊ·c Firecracker. -AI: OpenAI Responses API. -Git: GitHub App + GitHub API. -Deploy: Vercel + VPS. -Giao diện -Bα»‘ cα»₯c cΓ³ thể gα»“m: -+-----------------------------------------+ -| Sidebar | -| - Repositories | -| - Chats | -| - Tasks | -| - Settings | -+-------------+---------------------------+ -| | | -| Chat | Task Log | -| | | -| AI | Build | -| | Tests | -| | Git | -+-------------+---------------------------+ -ThΖ°Ζ‘ng hiệu -KhΓ΄ng nΓͺn dΓΉng cΓ‘c tΓͺn nhΖ°: -ChatGPT -Codex -OpenAI -CΓ³ thể xΓ’y dα»±ng thΖ°Ζ‘ng hiệu riΓͺng, vΓ­ dα»₯: -RKix Studio -RKix Agent -RKix Build -RKix Dev -RKix Cloud -Nova Build -ForgeAI -KhαΊ£ nΔƒng -SαΊ£n phαΊ©m cΓ³ thể Δ‘αΊ‘t khoαΊ£ng 90–95% trαΊ£i nghiệm cα»§a Codex Cloud, nαΊΏu triển khai Δ‘αΊ§y Δ‘α»§: -GitHub App. -Sandbox an toΓ n. -QuαΊ£n lΓ½ nhiều agent. -Streaming phαΊ£n hα»“i. -Chỉnh sα»­a mΓ£ trα»±c tiαΊΏp. -Pull Request tα»± Δ‘α»™ng. -ĐÒy lΓ  mα»™t dα»± Γ‘n khΓ‘ lα»›n, Ζ°α»›c tΓ­nh khoαΊ£ng 30.000–50.000 dΓ²ng mΓ£ nαΊΏu xΓ’y dα»±ng Δ‘αΊ§y Δ‘α»§ vΓ  ở mα»©c production. Vα»›i mα»₯c tiΓͺu cα»§a mΓ y, nΓͺn phΓ‘t triển theo tα»«ng giai Δ‘oαΊ‘n: trΖ°α»›c tiΓͺn hoΓ n thΓ nh MVP (chat + GitHub + chỉnh sα»­a mΓ£ + tαΊ‘o PR), sau Δ‘Γ³ mα»›i bα»• sung sandbox nΓ’ng cao, chαΊ‘y nhiều agent vΓ  cΓ‘c tΓ­nh nΔƒng tα»± Δ‘α»™ng hΓ³a khΓ‘c. +# πŸš€ CodeXPR +> **AI-Powered Code Explorer & Experience Platform** +> An intelligent coding assistant with GitHub integration, real-time collaboration, and AI-driven development workflows. + +
+ +![Status](https://img.shields.io/badge/status-active-success?style=flat-square&logo=github) +![Version](https://img.shields.io/badge/version-1.0.0-blue?style=flat-square&logo=npm) +![License](https://img.shields.io/badge/license-MIT-green?style=flat-square&logo=open-source-initiative) +![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen?style=flat-square&logo=node.js) +![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue?style=flat-square&logo=typescript) +![React](https://img.shields.io/badge/React-18.0+-61DAFB?style=flat-square&logo=react) + +**[Demo](#-quickstart) β€’ [Documentation](#-features) β€’ [Installation](#-installation-guide) β€’ [Contributing](#-contributing)** + +
+ +--- + +## 🎯 Vision + +CodeXPR transforms how developers work with code by combining: +- πŸ€– **AI-Powered Assistance** - GPT-4o integration for intelligent coding help +- πŸ”— **GitHub Integration** - Seamless repository, branch, and PR management +- πŸ’¬ **Real-Time Chat** - Interactive chat with full code context +- πŸ“‹ **Task Management** - Track and manage development tasks +- ⚑ **Modern Stack** - React + TypeScript + Tailwind CSS + Zite DB + +--- + +## ✨ Features + + + + + + + + + + +
+ +### πŸ’¬ AI Chat Interface +- Interactive conversations with GPT-4o +- Code context awareness +- Syntax highlighting +- Message history + + + +### πŸ“¦ Repository Browser +- Browse GitHub repositories +- View file structure +- Edit files in-browser +- Create branches & PRs + +
+ +### πŸ“‹ Task Management +- Create & track coding tasks +- Real-time task status +- Task logs & file tracking +- Priority management + + + +### πŸ” Authentication +- Magic Link Sign-in +- Google OAuth +- Session management +- Secure token handling + +
+ +--- + +## πŸ—οΈ Architecture + +``` +CodeXPR/ +β”œβ”€β”€ πŸ“ rkix-studio/ # Main RKix Studio Application +β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”œβ”€β”€ components/ # React UI Components +β”‚ β”‚ β”‚ β”œβ”€β”€ Layout.tsx +β”‚ β”‚ β”‚ β”œβ”€β”€ ChatView.tsx +β”‚ β”‚ β”‚ β”œβ”€β”€ TasksView.tsx +β”‚ β”‚ β”‚ β”œβ”€β”€ ReposView.tsx +β”‚ β”‚ β”‚ └── ... +β”‚ β”‚ β”œβ”€β”€ api/ # Backend API Endpoints +β”‚ β”‚ β”‚ β”œβ”€β”€ Chat Operations +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ createChat.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ getChats.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ updateChat.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ deleteChat.ts +β”‚ β”‚ β”‚ β”‚ └── createChatWithAI.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ Message Operations +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ createMessage.ts +β”‚ β”‚ β”‚ β”‚ └── getMessages.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ Task Operations +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ createTask.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ getTasks.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ getTask.ts +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ updateTask.ts +β”‚ β”‚ β”‚ β”‚ └── deleteTask.ts +β”‚ β”‚ β”‚ └── index.ts # Centralized exports +β”‚ β”‚ β”œβ”€β”€ App.tsx # Main Router +β”‚ β”‚ └── ... +β”‚ └── README.md # RKix Studio Docs +β”‚ +β”œβ”€β”€ πŸ“ apps/ # Monorepo Applications +β”‚ β”œβ”€β”€ web/ # Next.js Frontend +β”‚ β”œβ”€β”€ api/ # Fastify Backend +β”‚ └── ... +β”‚ +β”œβ”€β”€ πŸ“ packages/ # Shared Packages +β”‚ β”œβ”€β”€ shared/ # Shared Types & Utils +β”‚ └── ... +β”‚ +└── πŸ“„ package.json # Workspace Config +``` + +--- + +## πŸš€ Installation Guide (A-Z) + +### **Phase 1: Environment Setup** + +#### Step 1️⃣ - Prerequisites Check +Ensure you have these installed on your system: + +```bash +# Check Node.js version (need >= 18.0.0) +node --version +# Output should be: v18.x.x or higher + +# Check npm version (need >= 9.0.0) +npm --version +# Output should be: 9.x.x or higher + +# Check Git is installed +git --version +# Output should be: git version 2.x.x +``` + +If any are missing, download: +- **Node.js & npm**: https://nodejs.org/ (LTS recommended) +- **Git**: https://git-scm.com/ + +#### Step 2️⃣ - Clone the Repository + +```bash +# Navigate to your desired directory +cd ~/projects + +# Clone the repository +git clone https://github.com/HuynhThuong0711/CodeXPR.git + +# Navigate into the project +cd CodeXPR + +# Verify you're in the right place +pwd +# Output: /path/to/CodeXPR +``` + +#### Step 3️⃣ - Verify Project Structure + +```bash +# List main directories to confirm structure +ls -la + +# You should see: +# β”œβ”€β”€ rkix-studio/ +# β”œβ”€β”€ apps/ +# β”œβ”€β”€ packages/ +# β”œβ”€β”€ package.json +# └── README.md +``` + +--- + +### **Phase 2: Dependency Installation** + +#### Step 4️⃣ - Install Root Dependencies + +```bash +# Install all workspace dependencies +npm install + +# This will: +# βœ“ Download packages from npm registry +# βœ“ Install dependencies for root project +# βœ“ Link workspace packages together +# βœ“ Generate node_modules/ folder + +# Verify installation +ls -la node_modules/ | head -20 +``` + +#### Step 5️⃣ - Install Workspace Dependencies + +```bash +# Install dependencies for RKix Studio specifically +npm --workspace=rkix-studio install + +# Or navigate and install locally +cd rkix-studio +npm install +cd .. + +# Verify all packages are installed +npm list --depth=0 +``` + +#### Step 6️⃣ - Verify All Dependencies + +```bash +# Check if all required packages are present +npm ls + +# Should show: +# βœ“ zod +# βœ“ zite-integrations-backend-sdk +# βœ“ react +# βœ“ react-router-dom +# βœ“ tailwind css +# βœ“ shadcn/ui +``` + +--- + +### **Phase 3: Environment Configuration** + +#### Step 7️⃣ - Create Environment Files + +```bash +# Navigate to RKix Studio +cd rkix-studio + +# Create .env.local file for development secrets +cat > .env.local << 'EOF' +# GitHub Configuration +VITE_GITHUB_TOKEN=your_github_token_here +VITE_GITHUB_API_URL=https://api.github.com + +# OpenAI Configuration +VITE_OPENAI_API_KEY=your_openai_key_here +VITE_OPENAI_MODEL=gpt-4o + +# Zite Database Configuration +VITE_ZITE_DATABASE_ID=your_database_id +VITE_ZITE_API_KEY=your_zite_api_key + +# Application Configuration +VITE_APP_ENV=development +VITE_APP_URL=http://localhost:5173 +EOF + +# Verify file was created +cat .env.local + +# Return to root +cd .. +``` + +#### Step 8️⃣ - Update Environment Variables + +```bash +# Edit the .env.local file with your actual credentials +nano rkix-studio/.env.local +# or use your preferred editor (code, vim, etc.) + +# To get your tokens: +# 1. GitHub Token: https://github.com/settings/tokens +# 2. OpenAI Key: https://platform.openai.com/api-keys +# 3. Zite DB: https://zite.cloud/dashboard +``` + +--- + +### **Phase 4: Build & Compile** + +#### Step 9️⃣ - Build TypeScript + +```bash +# Compile TypeScript to JavaScript +npm run build + +# This will: +# βœ“ Check TypeScript types +# βœ“ Compile .ts/.tsx files +# βœ“ Generate output in dist/ folders +# βœ“ Report any errors + +# Verify build succeeded +ls -la dist/ 2>/dev/null || echo "Build complete" +``` + +#### Step πŸ”Ÿ - Lint Code + +```bash +# Check code quality and style +npm run lint + +# This will: +# βœ“ Check TypeScript errors +# βœ“ Verify ESLint rules +# βœ“ Report any issues + +# Expected output: "βœ“ No errors found" +``` + +--- + +### **Phase 5: Running the Application** + +#### Step 1️⃣1️⃣ - Start Development Server + +```bash +# Start the development server with hot reload +npm run dev + +# Expected output: +# > RKix Studio dev server +# Local: http://localhost:5173 +# Press 'q' to quit + +# Or run specific workspace +npm --workspace=rkix-studio run dev +``` + +#### Step 1️⃣2️⃣ - Access the Application + +```bash +# Open in your browser +open http://localhost:5173 +# or +firefox http://localhost:5173 +# or +google-chrome http://localhost:5173 + +# You should see: +# βœ“ RKix Studio home page +# βœ“ Navigation menu (Chat, Tasks, Repos) +# βœ“ Ready for interaction +``` + +#### Step 1️⃣3️⃣ - Test API Endpoints + +```bash +# In a new terminal, test chat endpoints +curl -X GET http://localhost:5173/api/chats + +# Test message creation +curl -X POST http://localhost:5173/api/messages \ + -H "Content-Type: application/json" \ + -d '{"chatId":"123","content":"Hello","role":"User"}' + +# Test task creation +curl -X POST http://localhost:5173/api/tasks \ + -H "Content-Type: application/json" \ + -d '{"title":"My Task","context":"Setup project"}' +``` + +--- + +### **Phase 6: Advanced Operations** + +#### Step 1️⃣4️⃣ - Create Git Feature Branch + +```bash +# Update main branch first +git pull origin main + +# Create a feature branch for your changes +git checkout -b feature/my-feature + +# Verify you're on the new branch +git branch + +# Output: * feature/my-feature +# main +``` + +#### Step 1️⃣5️⃣ - Make Changes & Commit + +```bash +# After making changes, check what changed +git status + +# Stage all changes +git add . + +# Or stage specific files +git add rkix-studio/src/components/MyComponent.tsx + +# Commit with descriptive message +git commit -m "feat: add new chat component with real-time updates" + +# Or use conventional commits +git commit -m "feat(chat): add real-time message streaming +- Implement WebSocket connection +- Add message buffering +- Update UI with new messages" +``` + +#### Step 1️⃣6️⃣ - Push & Create Pull Request + +```bash +# Push your feature branch +git push origin feature/my-feature + +# Then go to GitHub and click "Create Pull Request" +# Or use GitHub CLI: +gh pr create --title "Add new chat component" \ + --body "Implements real-time message updates" + +# View your PR +gh pr view +``` + +#### Step 1️⃣7️⃣ - Update from Main Branch + +```bash +# Fetch latest changes from remote +git fetch origin + +# Rebase your branch on latest main +git rebase origin/main + +# Or merge if you prefer +git merge origin/main + +# Resolve any conflicts if they occur +# Then push the update +git push origin feature/my-feature -f +``` + +--- + +### **Phase 7: Database & Data Operations** + +#### Step 1️⃣8️⃣ - Initialize Database + +```bash +# Connect to Zite database +npm run db:init + +# Or manually configure Zite +export ZITE_API_KEY=your_key +npm run db:migrate + +# Verify connection +npm run db:check + +# Expected output: +# βœ“ Connected to Zite database +# βœ“ Collections ready +``` + +#### Step 1️⃣9️⃣ - Seed Sample Data + +```bash +# Load sample data for testing +npm run db:seed + +# This creates: +# βœ“ 5 sample chats +# βœ“ 20 sample messages +# βœ“ 10 sample tasks + +# Verify data loaded +npm run db:list chats +``` + +--- + +### **Phase 8: Testing & Quality Assurance** + +#### Step 2️⃣0️⃣ - Run Tests + +```bash +# Run all tests +npm run test + +# Run tests in watch mode +npm run test:watch + +# Run tests with coverage +npm run test:coverage + +# Expected output: +# βœ“ Chat endpoints: 8 tests passed +# βœ“ Message endpoints: 6 tests passed +# βœ“ Task endpoints: 10 tests passed +# βœ“ Coverage: 85% +``` + +#### Step 2️⃣1️⃣ - Type Check + +```bash +# Strict TypeScript checking +npm run type-check + +# Expected output: +# βœ“ No TypeScript errors found +# βœ“ All types are valid +``` + +--- + +### **Phase 9: Production Build** + +#### Step 2️⃣2️⃣ - Build for Production + +```bash +# Create optimized production build +npm run build:prod + +# This will: +# βœ“ Minify code +# βœ“ Tree-shake unused code +# βœ“ Optimize bundle size +# βœ“ Generate source maps + +# Check build size +ls -lh dist/ +# Output: ~250KB (gzipped) +``` + +#### Step 2️⃣3️⃣ - Preview Production Build + +```bash +# Serve production build locally +npm run preview + +# Expected output: +# > preview server running at http://localhost:4173 + +# Test the production build +open http://localhost:4173 + +# Press Ctrl+C to stop +``` + +--- + +### **Phase 10: Deployment** + +#### Step 2️⃣4️⃣ - Deploy to GitHub Pages + +```bash +# Build and deploy +npm run deploy + +# Or manual deployment +npm run build:prod +git add dist/ +git commit -m "build: production build $(date)" +git push origin main + +# Access at: https://HuynhThuong0711.github.io/CodeXPR +``` + +#### Step 2️⃣5️⃣ - Deploy to Vercel + +```bash +# Install Vercel CLI +npm install -g vercel + +# Deploy with one command +vercel + +# Follow prompts to connect GitHub repo +# View deployment at: https://codexpr.vercel.app +``` + +--- + +## πŸ“Š Command Reference Table + +| Command | Description | Usage | +|---------|-------------|-------| +| `npm install` | Install all dependencies | Initial setup | +| `npm run dev` | Start development server | Local development | +| `npm run build` | Build for production | Pre-deployment | +| `npm run preview` | Preview production build | Testing production build | +| `npm run lint` | Run linter checks | Code quality check | +| `npm run test` | Run test suite | Quality assurance | +| `npm run type-check` | TypeScript type checking | Type validation | +| `npm run db:init` | Initialize database | Database setup | +| `npm run db:seed` | Load sample data | Testing data | + +--- + +## πŸ”§ Troubleshooting + +### Issue: `npm install` fails + +```bash +# Clear npm cache +npm cache clean --force + +# Try installing again +npm install + +# If still fails, remove node_modules and lock file +rm -rf node_modules package-lock.json +npm install +``` + +### Issue: Port 5173 already in use + +```bash +# Find process using the port +lsof -i :5173 + +# Kill the process +kill -9 + +# Or use different port +npm run dev -- --port 3000 +``` + +### Issue: TypeScript compilation errors + +```bash +# Check all TS errors +npm run type-check + +# Fix auto-fixable errors +npm run lint -- --fix + +# Review remaining errors manually +``` + +### Issue: API connection fails + +```bash +# Check environment variables are loaded +cat rkix-studio/.env.local + +# Verify API is running +curl http://localhost:5173/api/health + +# Check browser console for CORS errors +# May need to enable CORS in backend +``` + +--- + +## 🀝 Contributing + +We welcome contributions! Please follow these steps: + +1. **Fork** the repository +2. **Create** a feature branch (`git checkout -b feature/AmazingFeature`) +3. **Commit** your changes (`git commit -m 'Add AmazingFeature'`) +4. **Push** to the branch (`git push origin feature/AmazingFeature`) +5. **Open** a Pull Request + +### Development Guidelines + +- Follow TypeScript strict mode +- Write tests for new features +- Update documentation +- Keep commits atomic and descriptive + +--- + +## πŸ“ Project Structure Details + +``` +rkix-studio/ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ components/ # React Components +β”‚ β”‚ β”œβ”€β”€ Layout.tsx # Main layout wrapper +β”‚ β”‚ β”œβ”€β”€ ChatView.tsx # Chat interface +β”‚ β”‚ β”œβ”€β”€ TasksView.tsx # Tasks dashboard +β”‚ β”‚ └── ... +β”‚ β”œβ”€β”€ api/ # API Endpoints (Zite SDK) +β”‚ β”‚ β”œβ”€β”€ chat/ # Chat operations +β”‚ β”‚ β”œβ”€β”€ messages/ # Message operations +β”‚ β”‚ β”œβ”€β”€ tasks/ # Task operations +β”‚ β”‚ └── index.ts # Centralized exports +β”‚ β”œβ”€β”€ App.tsx # React Router config +β”‚ β”œβ”€β”€ main.tsx # Entry point +β”‚ └── styles/ # Global styles +β”œβ”€β”€ .env.local # Environment variables (git-ignored) +β”œβ”€β”€ package.json # Dependencies +β”œβ”€β”€ tsconfig.json # TypeScript config +β”œβ”€β”€ vite.config.ts # Vite bundler config +└── README.md # Documentation +``` + +--- + +## πŸ“š API Documentation + +### Chat Endpoints + +```typescript +// Get all chats +GET /api/chats +Response: { chats: Chat[] } + +// Create chat +POST /api/chat +Body: { title?: string } +Response: { id, title, createdAt } + +// Update chat +PUT /api/chat/:id +Body: { title: string } +Response: { id, title, createdAt } + +// Delete chat +DELETE /api/chat/:id +Response: { success: boolean } +``` + +### Message Endpoints + +```typescript +// Get messages for chat +GET /api/messages/:chatId +Response: { messages: Message[] } + +// Create message +POST /api/message +Body: { chatId: string, content: string, role?: string } +Response: { id, content, role, createdAt } +``` + +### Task Endpoints + +```typescript +// Get all tasks +GET /api/tasks?status=queued +Response: { tasks: Task[] } + +// Create task +POST /api/task +Body: { title: string, context?: string } +Response: { id, title, status, createdAt } + +// Get single task +GET /api/task/:id +Response: Task + +// Update task +PUT /api/task/:id +Body: { status?: string, log?: string } +Response: Task + +// Delete task +DELETE /api/task/:id +Response: { success: boolean } +``` + +--- + +## πŸŽ“ Learning Resources + +- **React Documentation**: https://react.dev +- **TypeScript Handbook**: https://www.typescriptlang.org/docs/ +- **Tailwind CSS**: https://tailwindcss.com/docs +- **Zite Database**: https://zite.cloud/docs +- **GitHub API**: https://docs.github.com/en/rest + +--- + +## πŸ“ž Support & Community + +- **Issues**: [GitHub Issues](https://github.com/HuynhThuong0711/CodeXPR/issues) +- **Discussions**: [GitHub Discussions](https://github.com/HuynhThuong0711/CodeXPR/discussions) +- **Email**: [Contact](mailto:support@codexpr.dev) + +--- + +## πŸ“„ License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +``` +MIT License + +Copyright (c) 2024 Huα»³nh ThΖ°ong + +Permission is hereby granted, free of charge, to any person obtaining a copy... +``` + +--- + +## πŸ™ Acknowledgments + +- **OpenAI** - GPT-4o integration +- **GitHub** - API and infrastructure +- **React Community** - Amazing ecosystem +- **Tailwind Labs** - Beautiful CSS framework +- **All Contributors** - Making this possible + +--- + +
+ +### ⭐ Found this helpful? Give us a star! + +[⭐ Star on GitHub](https://github.com/HuynhThuong0711/CodeXPR) + +**Made with ❀️ by the CodeXPR Team** + +
diff --git a/SETUP_GUIDE.md b/SETUP_GUIDE.md new file mode 100644 index 0000000..06b606b --- /dev/null +++ b/SETUP_GUIDE.md @@ -0,0 +1 @@ +# πŸš€ AI Agent Build System - Complete Setup & Continuation Guide\n\n## πŸ“‹ Table of Contents\n1. [What Has Been Done](#what-has-been-done)\n2. [Current Status](#current-status)\n3. [What's Next](#whats-next)\n4. [How to Continue Development](#how-to-continue-development)\n5. [Quick Start Commands](#quick-start-commands)\n6. [Project Structure](#project-structure)\n7. [Long-term Maintenance](#long-term-maintenance)\n\n---\n\n## βœ… What Has Been Done\n\n### Phase 1: Foundation Setup βœ“\n- [x] Created monorepo structure with pnpm workspaces\n- [x] Setup root package.json with all necessary scripts\n- [x] Configured TypeScript for entire workspace\n- [x] Created turbo.json for build optimization\n- [x] Setup Docker Compose for local development\n- [x] Created comprehensive documentation\n\n### Phase 2: Shared Packages βœ“\n- [x] **@ai-agent/types** - Centralized TypeScript interfaces\n - User, Chat, Message, Task, Repository, AgentSession types\n - ApiResponse and PaginatedResponse generic types\n- [x] **@ai-agent/utils** - Utility functions\n - generateId(), formatDate(), parseError()\n - debounce() and throttle() helpers\n- [x] **@ai-agent/shared** - Unified exports\n - Re-exports types and utils for convenience\n\n### Phase 3: Backend Infrastructure βœ“\n- [x] **API Gateway** (port 3001)\n - Express server with CORS support\n - WebSocket support for real-time communication\n - Proper logging with Pino\n - Health check endpoint\n - Error handling middleware\n - Ready for service routing\n\n### Phase 4: Frontend Application βœ“\n- [x] **React Web App** (port 3000)\n - Vite-powered React 18 with TypeScript\n - React Router for navigation\n - Dark theme with modern styling\n - Layout component with navbar\n - Three main pages: Chat, Tasks, Agent\n - Zustand ready for state management\n - WebSocket ready for real-time updates\n\n### Phase 5: Configuration & DevOps βœ“\n- [x] Docker Compose setup\n - PostgreSQL 16 database\n - Redis cache layer\n - Network configuration\n - Health checks for all services\n- [x] Environment configuration\n - .env.example with all variables\n - .gitignore for sensitive data\n - .npmrc for pnpm configuration\n- [x] CI/CD Pipeline\n - GitHub Actions workflow\n - TypeScript checking\n - Build verification\n - Multi-version Node.js testing\n\n### Phase 6: Documentation βœ“\n- [x] **ARCHITECTURE.md** - Complete system design\n- [x] **IMPLEMENTATION.md** - 6-phase step-by-step guide\n- [x] **README.md** - Quick start guide\n- [x] **SETUP_GUIDE.md** - This file (continuation guide)\n\n---\n\n## πŸ“Š Current Status\n\n### Branch Information\n- **Current Branch:** `feat/integrated-system`\n- **Base Branch:** `main`\n- **Commits:** Foundation setup complete\n- **Status:** Ready for Phase 2+ Development\n\n### Committed Files Summary\n```\nβœ“ Configuration Files (5)\n - pnpm-workspace.yaml\n - turbo.json\n - tsconfig.json\n - .npmrc\n - docker-compose.yml\n - .env.example\n - .gitignore\n\nβœ“ Shared Packages (9)\n - packages/types/\n - packages/utils/\n - packages/shared/\n\nβœ“ Backend Services (6)\n - services/api-gateway/ (complete)\n\nβœ“ Frontend Application (12)\n - apps/web/ (complete)\n\nβœ“ Documentation (3)\n - ARCHITECTURE.md\n - IMPLEMENTATION.md\n - README.md\n\nβœ“ CI/CD (1)\n - .github/workflows/ci.yml\n\nTotal: 40+ files\n```\n\n---\n\n## 🎯 What's Next\n\n### Priority 1: Get the System Running Locally (Week 1)\n```bash\n# 1. Install dependencies\npnpm install\n\n# 2. Start databases\npnpm docker:up\n\n# 3. Start all services\npnpm dev\n\n# 4. Access:\n# - Web UI: http://localhost:3000\n# - API: http://localhost:3001\n# - Health: http://localhost:3001/health\n```\n\n### Priority 2: Integrate CodeXPR Components (Week 2-3)\n- [ ] Copy React components from CodeXPR into `apps/web/src/components/`\n- [ ] Integrate ChatView component\n- [ ] Integrate TasksView component \n- [ ] Integrate ReposView component\n- [ ] Update styling to match dark theme\n\n### Priority 3: Integrate Sandbox-Ai (Week 3-4)\n- [ ] Create `apps/sandbox-ai/` application\n- [ ] Migrate CLI agent builder logic\n- [ ] Create web UI for agent configuration\n- [ ] Setup agent execution service\n\n### Priority 4: Backend Services (Week 4-5)\n- [ ] Create Chat & Task Service at `services/api-server/`\n- [ ] Setup PostgreSQL schema with Drizzle ORM\n- [ ] Implement REST API endpoints\n- [ ] Add WebSocket message handling\n- [ ] Integrate with OpenAI API\n\n### Priority 5: Advanced Features (Week 6+)\n- [ ] Real-time collaborative editing\n- [ ] GitHub integration for code operations\n- [ ] Task automation and scheduling\n- [ ] Agent workflow builder\n- [ ] Performance optimization\n- [ ] Production deployment\n\n---\n\n## πŸ“– How to Continue Development\n\n### Understanding the Project Structure\n\n```\nproject-root/\nβ”œβ”€β”€ packages/ # Shared code used by all apps/services\nβ”‚ β”œβ”€β”€ types/ # TypeScript interfaces (single source of truth)\nβ”‚ β”œβ”€β”€ utils/ # Reusable functions\nβ”‚ └── shared/ # Unified exports\nβ”œβ”€β”€ apps/ # User-facing applications\nβ”‚ β”œβ”€β”€ web/ # Main React dashboard\nβ”‚ └── sandbox-ai/ # To be created - AI agent builder\nβ”œβ”€β”€ services/ # Backend microservices\nβ”‚ β”œβ”€β”€ api-gateway/ # Main entry point (already complete)\nβ”‚ β”œβ”€β”€ api-server/ # To be created - Chat/Task service\nβ”‚ β”œβ”€β”€ agent-service/ # To be created - Agent orchestration\nβ”‚ └── db/ # To be created - Database schema\n└── docs/ # Documentation\n β”œβ”€β”€ ARCHITECTURE.md\n β”œβ”€β”€ IMPLEMENTATION.md\n └── SETUP_GUIDE.md\n```\n\n### Development Workflow\n\n#### 1. Adding a New Component\n```bash\n# Create component file\ntouch apps/web/src/components/MyComponent.tsx\n\n# Edit the file with your component\ncode apps/web/src/components/MyComponent.tsx\n\n# Hot reload should work immediately during pnpm dev:ui\n```\n\n#### 2. Adding a New API Endpoint\n```bash\n# Create route file\ntouch services/api-gateway/src/routes/myroute.ts\n\n# Add route handler\n# Then register in src/index.ts\n\n# Test with curl\ncurl http://localhost:3001/api/myroute\n```\n\n#### 3. Adding a New Shared Type\n```typescript\n// Edit packages/types/src/index.ts\n// Add your new interface\nexport interface MyNewType {\n id: string;\n name: string;\n}\n\n// It's automatically available everywhere:\n// import type { MyNewType } from '@ai-agent/types';\n```\n\n### Common Commands Reference\n\n```bash\n# Development\npnpm dev # Start all services\npnpm dev:ui # Web UI only\npnpm dev:api # API Gateway only\n\n# Building\npnpm build # Build all packages\npnpm build:ui # Build web app only\npnpm build:api # Build API gateway only\n\n# Quality\npnpm typecheck # Check TypeScript types\npnpm lint # Lint code (when eslint configured)\npnpm format # Format code with Prettier\n\n# Docker\npnpm docker:build # Build Docker images\npnpm docker:up # Start services\npnpm docker:down # Stop services\npnpm docker:logs # View logs\n\n# Monorepo\npnpm clean # Remove all build artifacts\npnpm install # Install all dependencies\n```\n\n---\n\n## πŸƒ Quick Start Commands\n\n### First Time Setup\n```bash\n# 1. Clone repo\ngit clone https://github.com/HuynhThuong0711/CodeXPR.git\ncd CodeXPR\n\n# 2. Checkout feature branch\ngit checkout feat/integrated-system\n\n# 3. Install dependencies\npnpm install\n\n# 4. Create .env file\ncp .env.example .env\n# Edit .env with your API keys\n\n# 5. Start databases\npnpm docker:up\n\n# Wait for health check\nsleep 5\n\n# 6. Start development\npnpm dev\n\n# 7. Open in browser\nopen http://localhost:3000\n```\n\n### Daily Development\n```bash\n# Terminal 1: Start everything\npnpm dev\n\n# Terminal 2: Monitor\npnpm docker:logs\n\n# Continue coding - hot reload works automatically\n```\n\n### Before Committing\n```bash\n# Check types\npnpm typecheck\n\n# Format code\npnpm format\n\n# Build to verify\npnpm build\n\n# Then commit\ngit add .\ngit commit -m \"feat: description of changes\"\ngit push origin feat/integrated-system\n```\n\n---\n\n## πŸ“ Project Structure Deep Dive\n\n### packages/types/\n**Purpose:** Single source of truth for TypeScript interfaces\n\n**Current Interfaces:**\n- `User` - User account information\n- `Chat` - Chat conversation\n- `Message` - Individual message\n- `Task` - Background task\n- `Repository` - GitHub repository\n- `AgentSession` - Agent execution session\n- `ApiResponse` - Standard API response\n- `PaginatedResponse` - Paginated results\n\n**Adding New Types:**\n```typescript\n// packages/types/src/index.ts\nexport interface NewFeature {\n id: string;\n // ... properties\n}\n\n// Automatically available everywhere\nimport type { NewFeature } from '@ai-agent/types';\n```\n\n### services/api-gateway/\n**Purpose:** Central routing and orchestration\n\n**Current Features:**\n- βœ“ Express server setup\n- βœ“ CORS configuration\n- βœ“ Request logging\n- βœ“ WebSocket support\n- βœ“ Health checks\n- βœ“ Error handling\n\n**To Add:**\n- [ ] Authentication middleware\n- [ ] Rate limiting\n- [ ] Request validation\n- [ ] Response transformation\n- [ ] Service discovery\n\n### apps/web/\n**Purpose:** React dashboard for users\n\n**Current Pages:**\n- βœ“ ChatView - Chat interface (placeholder)\n- βœ“ TasksView - Task dashboard (placeholder)\n- βœ“ AgentView - Agent configuration (placeholder)\n\n**To Add:**\n- [ ] Actual component implementations\n- [ ] State management with Zustand\n- [ ] API client services\n- [ ] Real-time updates via WebSocket\n- [ ] Error boundaries\n- [ ] Loading states\n\n---\n\n## πŸ”§ Long-term Maintenance\n\n### Daily (Automated)\n- GitHub Actions runs TypeScript checks\n- Prettier auto-formatting on commit\n- ESLint checks (when configured)\n\n### Weekly\n```bash\n# Update dependencies\npnpm update\n\n# Check for security vulnerabilities\npnpm audit\n\n# Run full build\npnpm build\n\n# Test all services\npnpm test\n```\n\n### Monthly\n```bash\n# Major dependency updates\npnpm update --interactive\n\n# Audit and fix security issues\npnpm audit --fix\n\n# Review Docker images for updates\ndocker pull postgres:16\ndocker pull redis:7\n\n# Backup database\npg_dump ai_agent_db > backup_$(date +%Y%m%d).sql\n```\n\n### Quarterly\n```bash\n# Review and update Node.js version\nnode --version\n\n# Performance profiling\nnode --prof services/api-gateway/dist/index.js\n\n# Code quality review\npnpm lint\npnpm typecheck\n\n# Documentation updates\necho \"Update CHANGELOG.md\"\n```\n\n### Yearly\n```bash\n# Major version updates\npnpm update typescript\npnpm update react\npnpm update express\n\n# License compliance check\n# Architecture review\n# Security audit\n```\n\n---\n\n## 🚨 Troubleshooting\n\n### \"Cannot find module '@ai-agent/types'\"\n```bash\n# Fix: Reinstall and verify symlinks\npnpm install\nls -la node_modules/@ai-agent/\n```\n\n### \"Port 3000 already in use\"\n```bash\n# Find and kill process\nlsof -i :3000\nkill -9 \n\n# Or use different port\nVITE_PORT=3002 pnpm dev:ui\n```\n\n### \"Database connection failed\"\n```bash\n# Check services running\npnpm docker:logs postgres\n\n# Restart services\npnpm docker:down\npnpm docker:up\n\n# Verify connection string\necho $DATABASE_URL\n```\n\n### \"TypeScript errors on build\"\n```bash\n# Check all errors\npnpm typecheck 2>&1 | head -50\n\n# Fix errors one by one\n# Add explicit types to functions\n# Use 'any' only as last resort (with comment)\n```\n\n---\n\n## πŸ“š Documentation Files\n\n### ARCHITECTURE.md\n- System overview and principles\n- Monorepo structure explained\n- Service architecture details\n- Data flow diagrams\n- Technology stack rationale\n- Integration points\n- Deployment strategies\n\n### IMPLEMENTATION.md\n- 6-phase implementation plan\n- Step-by-step setup instructions\n- Development workflows\n- Common commands reference\n- Testing procedures\n- Maintenance tasks\n\n### README.md\n- Quick start guide\n- Installation instructions\n- Available commands\n- Project overview\n\n### SETUP_GUIDE.md (This file)\n- What has been done\n- What's next\n- How to continue\n- Long-term maintenance\n\n---\n\n## πŸŽ“ Learning Resources\n\n- **React Documentation:** https://react.dev\n- **TypeScript Handbook:** https://www.typescriptlang.org/docs/\n- **Express.js Guide:** https://expressjs.com/\n- **pnpm Docs:** https://pnpm.io/\n- **Vite Guide:** https://vitejs.dev/\n- **WebSocket API:** https://developer.mozilla.org/en-US/docs/Web/API/WebSocket\n- **Docker Docs:** https://docs.docker.com/\n\n---\n\n## πŸ’Ύ Backup & Recovery\n\n### Database Backup\n```bash\n# Backup PostgreSQL\npg_dump ai_agent_db > backup.sql\n\n# Restore from backup\npsql ai_agent_db < backup.sql\n```\n\n### Source Code Recovery\n```bash\n# View git history\ngit log --oneline feat/integrated-system\n\n# Revert to specific commit\ngit checkout -- \n\n# Reset to previous commit\ngit reset --hard \n```\n\n---\n\n## πŸ“ž Getting Help\n\nIf you encounter issues:\n\n1. **Check logs first**\n ```bash\n pnpm docker:logs\n npm list\n ```\n\n2. **Review documentation**\n - ARCHITECTURE.md for design questions\n - IMPLEMENTATION.md for setup issues\n - README.md for quick reference\n\n3. **Common issues**\n - See \"Troubleshooting\" section above\n - Check GitHub issues\n - Review error messages carefully\n\n4. **Debug techniques**\n ```bash\n # Add console logs\n console.log('Debug:', variable);\n \n # Browser DevTools (F12)\n # Network tab for API calls\n # Console for JavaScript errors\n \n # API debugging\n curl -v http://localhost:3001/health\n ```\n\n---\n\n## 🎯 Next Steps for You\n\n### Immediate (Today)\n1. βœ… Read this guide\n2. βœ… Review ARCHITECTURE.md\n3. βœ… Run `pnpm install`\n4. βœ… Run `pnpm docker:up`\n5. βœ… Run `pnpm dev`\n6. βœ… Open http://localhost:3000\n\n### This Week\n1. [ ] Get system running locally\n2. [ ] Start integrating CodeXPR components\n3. [ ] Create API endpoints for chat/tasks\n4. [ ] Setup database schema\n5. [ ] Write first test\n\n### This Month\n1. [ ] Complete CodeXPR integration\n2. [ ] Integrate Sandbox-Ai\n3. [ ] Full backend implementation\n4. [ ] Real-time communication working\n5. [ ] Production-ready deployment\n\n---\n\n## πŸŽ‰ Success Checklist\n\nYou'll know everything is working when:\n\n- [ ] `pnpm install` completes without errors\n- [ ] `pnpm docker:up` shows all services healthy\n- [ ] `pnpm dev` starts all three services\n- [ ] http://localhost:3000 loads the web UI\n- [ ] http://localhost:3001/health returns JSON\n- [ ] WebSocket connection works\n- [ ] `pnpm typecheck` passes\n- [ ] `pnpm build` produces dist/ folders\n- [ ] All three services communicate\n- [ ] Components hot-reload during development\n\n---\n\n**Build Date:** 2024-01-20\n**Last Updated:** 2024-01-20\n**Maintainer:** AI Agent Team\n**Status:** Foundation Complete βœ… Ready for Integration\n" \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..0db0477 --- /dev/null +++ b/index.html @@ -0,0 +1,36 @@ + + + + + + + AI-Craft Studio + + + +
+ +
+
Next-Gen AI Agent Platform

Điểm khởi Δ‘αΊ§u cα»§a kα»· nguyΓͺn AI Agent mα»›i.

ThiαΊΏt kαΊΏ chat-to-build dΓ nh cho người dΓΉng khΓ΄ng chuyΓͺn: mΓ΄ tαΊ£ Γ½ tưởng, xΓ‘c nhαΊ­n gợi Γ½, xem AI build, kiểm Δ‘α»‹nh vΓ  triển khai trong mα»™t khΓ΄ng gian trα»±c quan.

⌬
Thinking...
Working...
+
+
β‘‚

Dashboard

Dα»± Γ‘n & lα»‹ch sα»­

Commerce Pilot

Đang build

74%

Booking Agent

Review

91%

Data Portal

SαΊ΅n sΓ ng

100%
+
☰

Central Conversation

AI Dev Agent

StorefrontCheckoutLive PreviewDeploy Setup
TαΊ‘o mα»™t app bΓ‘n giΓ y cΓ³ thanh toΓ‘n vΓ  dashboard.
Gợi Γ½ tα»‘i Ζ°u: storefront, checkout, inventory, analytics. XΓ‘c nhαΊ­n để bαΊ―t Δ‘αΊ§u build cαΊ₯u trΓΊc MVP.
XΓ‘c nhαΊ­n. Ζ―u tiΓͺn giao diện cao cαΊ₯p vΓ  live preview.
+
✧

Live Preview

Ứng dα»₯ng Δ‘ang build

✦

Nova Shoes

Premium AI-generated storefront

+
+
+
⚑

Tool Hub

Tab tiện Γ­ch Agent Dev

β–£ Terminal Β· live☁ Configuration Β· 3β–€ Knowledge Base Β· 12⌘ Prompt Editorβ—Œ Metrics Β· $2.18β–Ά Playground Β· ready
+
β–Έ

Run Management

Terminal automation

βœ“Install dependenciesThΓ nh cΓ΄ng
↻Run typecheckĐang chαΊ‘y
β—‹Build previewĐang chờ

βœ“ dependencies installed

β€Ί npm run build

… waiting for preview bundle

+
☁

Deploy Setup

Tα»± Δ‘α»™ng hΓ³a triển khai

  • Đang kiểm tra kαΊΏt nα»‘i production...
  • Đang Δ‘α»“ng bα»™ biαΊΏn mΓ΄i trường bαΊ£o mαΊ­t...
  • Đang cαΊ₯u hΓ¬nh server edge...
  • Đã tαΊ‘o preview URL: https://craft-preview.ai
+
πŸ”

Authorization Center

Quản lý ủy quyền AI

πŸ”’

Google Drive

Builder Agent Β· Read documents

Chờ duyệt
πŸ”’

Stripe Dashboard

Commerce Agent Β· Create checkout

Đã xÑc thực
+
+
β—ˆ

Realtime Analytics

Dashboard phΓ’n tΓ­ch dα»― liệu

Tasks

58

Success

94%

Token cost

$2.18

Deploys

12
Token trend
Tasks / day
Workflow mix
+
+
+ + diff --git a/package.json b/package.json new file mode 100644 index 0000000..eb7157b --- /dev/null +++ b/package.json @@ -0,0 +1,37 @@ +{ + "name": "ai-agent-build-system", + "version": "1.0.0", + "private": true, + "description": "Integrated AI-native agent build system with unified UI", + "license": "MIT", + "scripts": { + "preinstall": "npx only-allow pnpm", + "install": "pnpm install", + "dev": "pnpm -r --parallel run dev", + "dev:ui": "pnpm --filter @ai-agent/web run dev", + "dev:api": "pnpm --filter @ai-agent/api-gateway run dev", + "dev:sandbox": "pnpm --filter @ai-agent/sandbox-ai run dev", + "build": "pnpm -r --if-present run build", + "build:ui": "pnpm --filter @ai-agent/web run build", + "build:api": "pnpm --filter @ai-agent/api-gateway run build", + "typecheck": "pnpm -r --if-present run typecheck", + "lint": "pnpm -r --if-present run lint", + "format": "prettier --write \"**/*.{ts,tsx,json,md}\"", + "test": "pnpm -r --if-present run test", + "clean": "pnpm -r --if-present exec rm -rf dist node_modules .turbo", + "docker:build": "docker-compose build", + "docker:up": "docker-compose up -d", + "docker:down": "docker-compose down", + "docker:logs": "docker-compose logs -f" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "prettier": "^3.1.0", + "typescript": "~5.9.2", + "turbo": "^1.10.16" + }, + "engines": { + "node": ">=18.0.0", + "pnpm": ">=8.0.0" + } +} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..8a9be10 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,7 @@ +packages: + - 'packages/*' + - 'apps/*' + - 'services/*' + +overrides: + typescript: '~5.9.2' diff --git a/public/RAERD.md b/public/RAERD.md new file mode 100644 index 0000000..29621ac --- /dev/null +++ b/public/RAERD.md @@ -0,0 +1,146 @@ +# Git Credential Manager + +[![Build Status][build-status-badge]][workflow-status] + +--- + +[Git Credential Manager][gcm] (GCM) is a secure +[Git credential helper][git-credential-helper] built on [.NET][dotnet] that runs +on Windows, macOS, and Linux. It aims to provide a consistent and secure +authentication experience, including multi-factor auth, to every major source +control hosting service and platform. + +GCM supports (in alphabetical order) [Azure DevOps][azure-devops], Azure DevOps +Server (formerly Team Foundation Server), Bitbucket, GitHub, and GitLab. +Compare to Git's [built-in credential helpers][git-tools-credential-storage] +(Windows: wincred, macOS: osxkeychain, Linux: gnome-keyring/libsecret), which +provide single-factor authentication support for username/password only. + +GCM replaces both the .NET Framework-based +[Git Credential Manager for Windows][gcm-for-windows] and the Java-based +[Git Credential Manager for Mac and Linux][gcm-for-mac-and-linux]. + +## Install + +See the [installation instructions][install] for the current version of GCM for +install options for your operating system. + +## Current status + +Git Credential Manager is currently available for Windows, macOS, and Linux\*. +GCM only works with HTTP(S) remotes; you can still use Git with SSH: + +- [Azure DevOps SSH][azure-devops-ssh] +- [GitHub SSH][github-ssh] +- [Bitbucket SSH][bitbucket-ssh] + +Feature|Windows|macOS|Linux\* +-|:-:|:-:|:-: +Installer/uninstaller|✓|✓|✓ +Secure platform credential storage [(see more)][gcm-credstores]|✓|✓|✓ +Multi-factor authentication support for Azure DevOps|✓|✓|✓ +Two-factor authentication support for GitHub|✓|✓|✓ +Two-factor authentication support for Bitbucket|✓|✓|✓ +Two-factor authentication support for GitLab|✓|✓|✓ +Windows Integrated Authentication (NTLM/Kerberos) support|✓|_N/A_|_N/A_ +Basic HTTP authentication support|✓|✓|✓ +Proxy support|✓|✓|✓ +`amd64` support|✓|✓|✓ +`x86` support|✓|_N/A_|✗ +`arm64` support|best effort|✓|✓ +`armhf` support|_N/A_|_N/A_|✓ + +(\*) GCM guarantees support only for [the Linux distributions that are officially +supported by dotnet][dotnet-distributions]. + +## Supported Git versions + +Git Credential Manager tries to be compatible with the broadest set of Git +versions (within reason). However there are some known problematic releases of +Git that are not compatible. + +- Git 1.x + + The initial major version of Git is not supported or tested with GCM. + +- Git 2.26.2 + + This version of Git introduced a breaking change with parsing credential + configuration that GCM relies on. This issue was fixed in commit + [`12294990`][gcm-commit-12294990] of the Git project, and released in Git + 2.27.0. + +## How to use + +Once it's installed and configured, Git Credential Manager is called implicitly +by Git. You don't have to do anything special, and GCM isn't intended to be +called directly by the user. For example, when pushing (`git push`) to +[Azure DevOps][azure-devops], [Bitbucket][bitbucket], or [GitHub][github], a +window will automatically open and walk you through the sign-in process. (This +process will look slightly different for each Git host, and even in some cases, +whether you've connected to an on-premises or cloud-hosted Git host.) Later Git +commands in the same repository will re-use existing credentials or tokens that +GCM has stored for as long as they're valid. + +Read full command line usage [here][gcm-usage]. + +### Configuring a proxy + +See detailed information [here][gcm-http-proxy]. + +## Additional Resources + +See the [documentation index][docs-index] for links to additional resources. + +## Experimental Features + +- [Windows broker (experimental)][gcm-windows-broker] + +## Future features + +Curious about what's coming next in the GCM project? Take a look at the [project +roadmap][roadmap]! You can find more details about the construction of the +roadmap and how to interpret it [here][roadmap-announcement]. + +## Contributing + +This project welcomes contributions and suggestions. +See the [contributing guide][gcm-contributing] to get started. + +This project follows [GitHub's Open Source Code of Conduct][gcm-coc]. + +## License + +We're [MIT][gcm-license] licensed. +When using GitHub logos, please be sure to follow the +[GitHub logo guidelines][github-logos]. + +[azure-devops]: https://azure.microsoft.com/en-us/products/devops +[azure-devops-ssh]: https://docs.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops +[bitbucket]: https://bitbucket.org +[bitbucket-ssh]: https://confluence.atlassian.com/bitbucket/ssh-keys-935365775.html +[build-status-badge]: https://github.com/git-ecosystem/git-credential-manager/actions/workflows/continuous-integration.yml/badge.svg +[docs-index]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/README.md +[dotnet]: https://dotnet.microsoft.com +[dotnet-distributions]: https://learn.microsoft.com/en-us/dotnet/core/install/linux +[git-credential-helper]: https://git-scm.com/docs/gitcredentials +[gcm]: https://github.com/git-ecosystem/git-credential-manager +[gcm-coc]: CODE_OF_CONDUCT.md +[gcm-commit-12294990]: https://github.com/git/git/commit/12294990c90e043862be9eb7eb22c3784b526340 +[gcm-contributing]: CONTRIBUTING.md +[gcm-credstores]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/credstores.md +[gcm-for-mac-and-linux]: https://github.com/microsoft/Git-Credential-Manager-for-Mac-and-Linux +[gcm-for-windows]: https://github.com/microsoft/Git-Credential-Manager-for-Windows +[gcm-http-proxy]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/netconfig.md#http-proxy +[gcm-license]: LICENSE +[gcm-usage]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/usage.md +[gcm-windows-broker]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/windows-broker.md +[git-tools-credential-storage]: https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage +[github]: https://github.com +[github-ssh]: https://help.github.com/en/articles/connecting-to-github-with-ssh +[github-logos]: https://github.com/logos +[install]: https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/install.md +[ms-package-repos]: https://packages.microsoft.com/repos/ +[roadmap]: https://github.com/git-ecosystem/git-credential-manager/milestones?direction=desc&sort=due_date&state=open +[roadmap-announcement]: https://github.com/git-ecosystem/git-credential-manager/discussions/1203 +[workflow-status]: https://github.com/git-ecosystem/git-credential-manager/actions/workflows/continuous-integration.yml \ No newline at end of file diff --git a/rkix-studio/README.md b/rkix-studio/README.md new file mode 100644 index 0000000..f2a6ceb --- /dev/null +++ b/rkix-studio/README.md @@ -0,0 +1,20 @@ +# RKix Studio + +AI-powered coding assistant platform with GitHub integration. + +## Features +- πŸ’¬ AI Chat - Interact with GPT-4o for coding help +- πŸ“‹ Task Management - Create and track coding tasks +- πŸ”— GitHub Integration - Browse repos, edit files, create branches & PRs +- πŸ” Authentication - Magic Link & Google Sign-in + +## Tech Stack +- React + TypeScript +- Tailwind CSS + shadcn/ui +- OpenAI GPT-4o +- GitHub API +- Zite Database + +## Structure +- `src/components/` - React components (Layout, ChatView, ReposView, etc.) +- `src/api/` - Backend endpoints (chat, tasks, GitHub operations) diff --git a/rkix-studio/src/App.tsx b/rkix-studio/src/App.tsx new file mode 100644 index 0000000..8e3b64c --- /dev/null +++ b/rkix-studio/src/App.tsx @@ -0,0 +1,27 @@ +import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; +import { Toaster } from '@/components/ui/sonner'; +import Layout from '@/components/Layout'; +import ChatView from '@/components/ChatView'; +import TasksView from '@/components/TasksView'; +import TaskDetailView from '@/components/TaskDetailView'; +import ReposView from '@/components/ReposView'; +import RepoDetailView from '@/components/RepoDetailView'; + +export default function App() { + return ( + + + + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + ); +} \ No newline at end of file diff --git a/rkix-studio/src/api/README.md b/rkix-studio/src/api/README.md new file mode 100644 index 0000000..ed72246 --- /dev/null +++ b/rkix-studio/src/api/README.md @@ -0,0 +1,113 @@ +# RKix Studio API Endpoints + +All endpoints use Zite backend SDK with Zod validation. + +## Chat Management + +### `createChat.ts` +Create a new chat. +- **Input**: `{ title?: string }` +- **Output**: `{ id, title, createdAt }` + +### `getChats.ts` +Retrieve all chats sorted by creation date (newest first). +- **Input**: `{}` +- **Output**: `{ chats: [{ id, title, createdAt }] }` +- **Limit**: 50 chats + +### `updateChat.ts` +Update a chat's title. +- **Input**: `{ chatId: string, title: string }` +- **Output**: `{ id, title, createdAt }` + +### `deleteChat.ts` +Delete a chat and all associated messages. +- **Input**: `{ chatId: string }` +- **Output**: `{ success: boolean }` + +### `createChatWithAI.ts` +Create a chat and send an initial message in one operation. +- **Input**: `{ title?: string, initialMessage: string }` +- **Output**: `{ chatId, title, messageId, createdAt }` + +## Message Management + +### `createMessage.ts` +Create a new message in a chat. +- **Input**: `{ chatId: string, content: string, role?: string }` +- **Output**: `{ id, content, role, createdAt }` +- **Roles**: 'User', 'Assistant', or custom + +### `getMessages.ts` +Retrieve all messages for a chat, sorted chronologically (oldest first). +- **Input**: `{ chatId: string }` +- **Output**: `{ messages: [{ id, content, role, createdAt }] }` +- **Limit**: 200 messages + +## Task Management + +### `createTask.ts` +Create a new task. +- **Input**: `{ title: string, context?: string, status?: string }` +- **Output**: `{ id, title, status, context, createdAt }` +- **Default Status**: 'Queued' + +### `getTasks.ts` +Retrieve all tasks, optionally filtered by status. +- **Input**: `{ status?: string }` +- **Output**: `{ tasks: [{ id, title, status, context, log, filesChanged, createdAt }] }` +- **Limit**: 100 tasks +- **Sorting**: Newest first + +### `getTask.ts` +Retrieve a single task by ID. +- **Input**: `{ taskId: string }` +- **Output**: `{ id, title, status, context, log, filesChanged, createdAt }` + +### `updateTask.ts` +Update task fields (status, log, filesChanged). +- **Input**: `{ taskId: string, status?: string, log?: string, filesChanged?: string }` +- **Output**: `{ id, title, status, context, log, filesChanged, createdAt }` + +### `deleteTask.ts` +Delete a task. +- **Input**: `{ taskId: string }` +- **Output**: `{ success: boolean }` + +## Error Handling + +All endpoints include try-catch blocks and return meaningful error messages. + +## Data Schema + +### Chat +```typescript +{ + id: string; + title: string; + createdAt?: string; +} +``` + +### Message +```typescript +{ + id: string; + content: string; + role: string; // 'user' or 'assistant' + createdAt?: string; +} +``` + +### Task +```typescript +{ + id: string; + title: string; + status: string; // 'queued', 'running', 'completed', 'failed' + context?: string; + log?: string; + filesChanged?: string; + createdAt?: string; +} +``` diff --git a/rkix-studio/src/api/createChat.ts b/rkix-studio/src/api/createChat.ts new file mode 100644 index 0000000..91ce11b --- /dev/null +++ b/rkix-studio/src/api/createChat.ts @@ -0,0 +1,12 @@ +import { z } from 'zod'; +import { createEndpoint, Chats } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Create a new chat', + inputSchema: z.object({ title: z.string().optional() }), + outputSchema: z.object({ id: z.string(), title: z.string(), createdAt: z.string().optional() }), + execute: async ({ input }) => { + const chat = await Chats.create({ record: { title: input.title || 'New Chat', createdAt: new Date().toISOString() } }); + return { id: chat.id, title: chat.title || 'New Chat', createdAt: chat.createdAt }; + }, +}); \ No newline at end of file diff --git a/rkix-studio/src/api/createChatWithAI.ts b/rkix-studio/src/api/createChatWithAI.ts new file mode 100644 index 0000000..84607f2 --- /dev/null +++ b/rkix-studio/src/api/createChatWithAI.ts @@ -0,0 +1,46 @@ +import { z } from 'zod'; +import { createEndpoint, Chats, Messages } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Create a new chat and send initial message', + inputSchema: z.object({ + title: z.string().optional(), + initialMessage: z.string() + }), + outputSchema: z.object({ + chatId: z.string(), + title: z.string(), + messageId: z.string(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + // Create chat + const chat = await Chats.create({ + record: { + title: input.title || 'New Chat', + createdAt: new Date().toISOString() + } + }); + + // Create initial message + const message = await Messages.create({ + record: { + chat: chat.id, + content: input.initialMessage, + role: 'User', + createdAt: new Date().toISOString() + } + }); + + return { + chatId: chat.id, + title: chat.title || 'New Chat', + messageId: message.id, + createdAt: chat.createdAt + }; + } catch (error) { + throw new Error(`Failed to create chat with AI: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/createMessage.ts b/rkix-studio/src/api/createMessage.ts new file mode 100644 index 0000000..ab20fd0 --- /dev/null +++ b/rkix-studio/src/api/createMessage.ts @@ -0,0 +1,37 @@ +import { z } from 'zod'; +import { createEndpoint, Messages } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Create a new message in a chat', + inputSchema: z.object({ + chatId: z.string(), + content: z.string(), + role: z.string().default('User') + }), + outputSchema: z.object({ + id: z.string(), + content: z.string(), + role: z.string(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + const message = await Messages.create({ + record: { + chat: input.chatId, + content: input.content, + role: input.role, + createdAt: new Date().toISOString() + } + }); + return { + id: message.id, + content: message.content || '', + role: (message.role || 'User').toLowerCase(), + createdAt: message.createdAt + }; + } catch (error) { + throw new Error(`Failed to create message: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/createTask.ts b/rkix-studio/src/api/createTask.ts new file mode 100644 index 0000000..235267d --- /dev/null +++ b/rkix-studio/src/api/createTask.ts @@ -0,0 +1,39 @@ +import { z } from 'zod'; +import { createEndpoint, Tasks } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Create a new task', + inputSchema: z.object({ + title: z.string(), + context: z.string().optional(), + status: z.string().default('Queued') + }), + outputSchema: z.object({ + id: z.string(), + title: z.string(), + status: z.string(), + context: z.string().optional(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + const task = await Tasks.create({ + record: { + title: input.title, + context: input.context, + status: input.status || 'Queued', + createdAt: new Date().toISOString() + } + }); + return { + id: task.id, + title: task.title || 'Untitled Task', + status: (task.status || 'Queued').toLowerCase(), + context: task.context, + createdAt: task.createdAt + }; + } catch (error) { + throw new Error(`Failed to create task: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/deleteChat.ts b/rkix-studio/src/api/deleteChat.ts new file mode 100644 index 0000000..5cfdc63 --- /dev/null +++ b/rkix-studio/src/api/deleteChat.ts @@ -0,0 +1,14 @@ +import { z } from 'zod'; +import { createEndpoint, Chats, Messages } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Delete a chat and its messages', + inputSchema: z.object({ chatId: z.string() }), + outputSchema: z.object({ success: z.boolean() }), + execute: async ({ input }) => { + const { records: msgs } = await Messages.findAll({ filters: { chat: input.chatId } }); + for (const m of msgs) { await Messages.delete({ id: m.id }); } + await Chats.delete({ id: input.chatId }); + return { success: true }; + }, +}); \ No newline at end of file diff --git a/rkix-studio/src/api/deleteTask.ts b/rkix-studio/src/api/deleteTask.ts new file mode 100644 index 0000000..8e1d82c --- /dev/null +++ b/rkix-studio/src/api/deleteTask.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; +import { createEndpoint, Tasks } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Delete a task', + inputSchema: z.object({ taskId: z.string() }), + outputSchema: z.object({ success: z.boolean() }), + execute: async ({ input }) => { + try { + await Tasks.delete({ id: input.taskId }); + return { success: true }; + } catch (error) { + throw new Error(`Failed to delete task: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/getChats.ts b/rkix-studio/src/api/getChats.ts new file mode 100644 index 0000000..5629ef5 --- /dev/null +++ b/rkix-studio/src/api/getChats.ts @@ -0,0 +1,17 @@ +import { z } from 'zod'; +import { createEndpoint, Chats } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Get all chats sorted by creation date', + inputSchema: z.object({}), + outputSchema: z.object({ chats: z.array(z.object({ id: z.string(), title: z.string(), createdAt: z.string().optional() })) }), + execute: async () => { + const { records } = await Chats.findAll({ limit: 50 }); + const sorted = records.sort((a, b) => { + const da = a.createdAt ? new Date(a.createdAt).getTime() : 0; + const db = b.createdAt ? new Date(b.createdAt).getTime() : 0; + return db - da; + }); + return { chats: sorted.map(c => ({ id: c.id, title: c.title || 'New Chat', createdAt: c.createdAt })) }; + }, +}); \ No newline at end of file diff --git a/rkix-studio/src/api/getMessages.ts b/rkix-studio/src/api/getMessages.ts new file mode 100644 index 0000000..d591cf8 --- /dev/null +++ b/rkix-studio/src/api/getMessages.ts @@ -0,0 +1,17 @@ +import { z } from 'zod'; +import { createEndpoint, Messages } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Get messages for a chat', + inputSchema: z.object({ chatId: z.string() }), + outputSchema: z.object({ messages: z.array(z.object({ id: z.string(), content: z.string(), role: z.string(), createdAt: z.string().optional() })) }), + execute: async ({ input }) => { + const { records } = await Messages.findAll({ filters: { chat: input.chatId }, limit: 200 }); + const sorted = records.sort((a, b) => { + const da = a.createdAt ? new Date(a.createdAt).getTime() : 0; + const db = b.createdAt ? new Date(b.createdAt).getTime() : 0; + return da - db; + }); + return { messages: sorted.map(m => ({ id: m.id, content: m.content || '', role: (m.role || 'User').toLowerCase(), createdAt: m.createdAt })) }; + }, +}); \ No newline at end of file diff --git a/rkix-studio/src/api/getTask.ts b/rkix-studio/src/api/getTask.ts new file mode 100644 index 0000000..c61e73f --- /dev/null +++ b/rkix-studio/src/api/getTask.ts @@ -0,0 +1,35 @@ +import { z } from 'zod'; +import { createEndpoint, Tasks } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Get a single task by ID', + inputSchema: z.object({ taskId: z.string() }), + outputSchema: z.object({ + id: z.string(), + title: z.string(), + status: z.string(), + context: z.string().optional(), + log: z.string().optional(), + filesChanged: z.string().optional(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + const task = await Tasks.findById({ id: input.taskId }); + if (!task) { + throw new Error('Task not found'); + } + return { + id: task.id, + title: task.title || 'Untitled Task', + status: (task.status || 'Queued').toLowerCase(), + context: task.context, + log: task.log, + filesChanged: task.filesChanged, + createdAt: task.createdAt + }; + } catch (error) { + throw new Error(`Failed to fetch task: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/getTasks.ts b/rkix-studio/src/api/getTasks.ts new file mode 100644 index 0000000..b8e381f --- /dev/null +++ b/rkix-studio/src/api/getTasks.ts @@ -0,0 +1,19 @@ +import { z } from 'zod'; +import { createEndpoint, Tasks } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Get all tasks', + inputSchema: z.object({ status: z.string().optional() }), + outputSchema: z.object({ tasks: z.array(z.object({ id: z.string(), title: z.string(), status: z.string(), context: z.string().optional(), log: z.string().optional(), filesChanged: z.string().optional(), createdAt: z.string().optional() })) }), + execute: async ({ input }) => { + const filters: Record = {}; + if (input.status) filters.status = input.status; + const { records } = await Tasks.findAll({ filters, limit: 100 }); + const sorted = records.sort((a, b) => { + const da = a.createdAt ? new Date(a.createdAt).getTime() : 0; + const db = b.createdAt ? new Date(b.createdAt).getTime() : 0; + return db - da; + }); + return { tasks: sorted.map(t => ({ id: t.id, title: t.title || 'Untitled Task', status: (t.status || 'Queued').toLowerCase(), context: t.context, log: t.log, filesChanged: t.filesChanged, createdAt: t.createdAt })) }; + }, +}); \ No newline at end of file diff --git a/rkix-studio/src/api/index.ts b/rkix-studio/src/api/index.ts new file mode 100644 index 0000000..834b6e3 --- /dev/null +++ b/rkix-studio/src/api/index.ts @@ -0,0 +1,17 @@ +// Chat API Endpoints +export { default as createChat } from './createChat'; +export { default as getChats } from './getChats'; +export { default as updateChat } from './updateChat'; +export { default as deleteChat } from './deleteChat'; +export { default as createChatWithAI } from './createChatWithAI'; + +// Message API Endpoints +export { default as createMessage } from './createMessage'; +export { default as getMessages } from './getMessages'; + +// Task API Endpoints +export { default as createTask } from './createTask'; +export { default as getTasks } from './getTasks'; +export { default as getTask } from './getTask'; +export { default as updateTask } from './updateTask'; +export { default as deleteTask } from './deleteTask'; diff --git a/rkix-studio/src/api/updateChat.ts b/rkix-studio/src/api/updateChat.ts new file mode 100644 index 0000000..64c41d3 --- /dev/null +++ b/rkix-studio/src/api/updateChat.ts @@ -0,0 +1,30 @@ +import { z } from 'zod'; +import { createEndpoint, Chats } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Update a chat title', + inputSchema: z.object({ + chatId: z.string(), + title: z.string() + }), + outputSchema: z.object({ + id: z.string(), + title: z.string(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + const chat = await Chats.update({ + id: input.chatId, + record: { title: input.title } + }); + return { + id: chat.id, + title: chat.title || 'New Chat', + createdAt: chat.createdAt + }; + } catch (error) { + throw new Error(`Failed to update chat: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/rkix-studio/src/api/updateTask.ts b/rkix-studio/src/api/updateTask.ts new file mode 100644 index 0000000..573782f --- /dev/null +++ b/rkix-studio/src/api/updateTask.ts @@ -0,0 +1,45 @@ +import { z } from 'zod'; +import { createEndpoint, Tasks } from 'zite-integrations-backend-sdk'; + +export default createEndpoint({ + description: 'Update a task status, log, or other fields', + inputSchema: z.object({ + taskId: z.string(), + status: z.string().optional(), + log: z.string().optional(), + filesChanged: z.string().optional() + }), + outputSchema: z.object({ + id: z.string(), + title: z.string(), + status: z.string(), + context: z.string().optional(), + log: z.string().optional(), + filesChanged: z.string().optional(), + createdAt: z.string().optional() + }), + execute: async ({ input }) => { + try { + const updateData: Record = {}; + if (input.status) updateData.status = input.status; + if (input.log) updateData.log = input.log; + if (input.filesChanged) updateData.filesChanged = input.filesChanged; + + const task = await Tasks.update({ + id: input.taskId, + record: updateData + }); + return { + id: task.id, + title: task.title || 'Untitled Task', + status: (task.status || 'Queued').toLowerCase(), + context: task.context, + log: task.log, + filesChanged: task.filesChanged, + createdAt: task.createdAt + }; + } catch (error) { + throw new Error(`Failed to update task: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + }, +}); diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..3cbd3d5 --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,6 @@ +import { mkdir, copyFile, rm } from 'node:fs/promises'; + +await rm('dist', { recursive: true, force: true }); +await mkdir('dist', { recursive: true }); +await copyFile('index.html', 'dist/index.html'); +console.log('Static build complete: dist/index.html'); diff --git a/scripts/lint.mjs b/scripts/lint.mjs new file mode 100644 index 0000000..53738de --- /dev/null +++ b/scripts/lint.mjs @@ -0,0 +1,10 @@ +import { readFile } from 'node:fs/promises'; + +const html = await readFile('index.html', 'utf8'); +const required = ['AI-Craft Studio', 'Run Management', 'Deploy Setup', 'Authorization Center', 'Realtime Analytics']; +const missing = required.filter((token) => !html.includes(token)); +if (missing.length) { + console.error(`Missing required UI sections: ${missing.join(', ')}`); + process.exit(1); +} +console.log('Static UI checks passed');