Skip to content

iwangbowen/cyber-chess-roast

Repository files navigation

♟️ Cyber Chess Roast

A real-time chess AI commentary system powered by GitHub Copilot SDK. As you play, AI analyzes and comments on every move like a professional commentator.

License Node TypeScript

✨ Features

  • 🤖 Real-time AI Commentary: Professional game commentary using GitHub Copilot's advanced models (GPT-5, Claude Sonnet 4.5)
  • ♟️ Complete Chess Engine: Full chess engine based on chess.js
  • 🎨 Clean UI: Modern, responsive interface built with React + CSS
  • 📡 Real-time Communication: Low-latency bidirectional communication via WebSocket
  • 🎙️ Streaming Response: AI commentary displayed in real-time with typewriter effect
  • 🔧 Custom Tools: Integrated professional tools for game state queries
  • 📊 Game Analysis: Automatic identification of opening, middlegame, and endgame phases
  • 🎬 Game Summary: Generate complete game summaries and reviews

🚀 Quick Start

Prerequisites

  1. Node.js: >= 18.0.0
  2. GitHub Copilot CLI: Installed and authenticated
  3. GitHub Copilot Subscription: Valid paid subscription required

Install Copilot CLI

# Install via npm
npm install -g @github/copilot-cli

# Or use GitHub CLI extension
gh extension install github/gh-copilot

# Authenticate
copilot auth login

# Verify installation
copilot --version

Install Project Dependencies

npm install

Configure Environment Variables

# Copy example configuration
cp .env.example .env

# Edit .env file (optional)
# PORT=3000
# LOG_LEVEL=info

Start Development Server

# Start in development mode (concurrent frontend and backend)
npm run dev

# Or start separately
npm run dev:client  # Frontend dev server (Vite)
npm run dev:server  # Backend server (Node.js with tsx)

Application will run at:

📖 User Guide

Basic Operations

  1. Start Commentary: The AI commentator is ready when you open the app
  2. Make Moves: Click a piece to select it, then click the target square to move
  3. Real-time Commentary: After each move, AI provides real-time analysis and commentary
  4. Generate Summary: After at least 5 moves, click "Summary" to get game review
  5. Reset Game: Click "Reset" to start a new game

Interface Overview

┌─────────────────────────────────────────────────┐
│           ♟️ Cyber Chess Roast                 │
│          Real-time Chess AI Commentary          │
├─────────────────────────────────────────────────┤
│  Game Info   │        AI Commentary Panel       │
│  ┌─────────┐ │  ┌──────────────────────────┐   │
│  │ Round: 5 │ │  │ 🎤 AI Commentary ● Connected │   │
│  │ Moves: 9 │ │  │                          │   │
│  │ Phase:Mid│ │  │  [Streaming content...]  │   │
│  └─────────┘ │  │  ▊                       │   │
│              │  └──────────────────────────┘   │
│  ┌─────────┐ │                                 │
│  │         │ │                                 │
│  │  Board  │ │                                 │
│  │         │ │                                 │
│  └─────────┘ │                                 │
│              │                                 │
│  ┌─────────┐ ┌───────────┐                    │
│  │🔄 Reset  │ │📊 Summary │                    │
│  └─────────┘ └───────────┘                    │
└─────────────────────────────────────────────────┘

🏗️ Project Structure

cyber-chess-roast/
├── src/
│   ├── client/              # React frontend
│   │   ├── components/      # React components
│   │   │   ├── Chessboard.tsx
│   │   │   ├── Chessboard.css
│   │   │   ├── Commentary.tsx
│   │   │   └── Commentary.css
│   │   ├── hooks/           # React Hooks
│   │   │   ├── useChessGame.ts
│   │   │   ├── useStockfish.ts
│   │   │   └── useWebSocket.ts
│   │   ├── App.tsx
│   │   ├── App.css
│   │   ├── main.tsx
│   │   └── index.css
│   │
│   └── server/              # Node.js backend
│       ├── commentator.ts   # Copilot SDK integration
│       ├── websocket.ts     # WebSocket server
│       ├── types.ts         # TypeScript type definitions
│       └── index.ts         # Server entry point
│
├── public/                  # Static assets
├── index.html               # HTML template
├── package.json
├── tsconfig.json
├── tsconfig.node.json
├── vite.config.ts
├── .env.example
└── README.md

🔧 Tech Stack

Frontend

  • React 18: UI framework
  • TypeScript: Type safety
  • chess.js: Chess logic engine
  • Vite: Build tool
  • WebSocket Client: Real-time communication

Backend

  • Node.js: Runtime environment
  • TypeScript: Type safety
  • Express: Web framework
  • Socket.IO: WebSocket server
  • GitHub Copilot SDK: AI engine
  • chess.js: Game validation

📚 Core API Usage

GitHub Copilot SDK Initialization

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({
  logLevel: "warning",
  autoStart: true,
  autoRestart: true
});

await client.start();

Create Session

const session = await client.createSession({
  model: "gpt-4o",
  streaming: true,
  tools: [getGameStateTool, analyzePositionTool],
  systemMessage: {
    content: "You are a professional chess commentator..."
  }
});

Streaming Response

session.on((event) => {
  if (event.type === "assistant.message_delta") {
    // Handle incremental content
    process.stdout.write(event.data.deltaContent);
  }

  if (event.type === "session.idle") {
    // Commentary complete
    console.log("Commentary complete");
  }
});

await session.sendAndWait({ prompt: "Comment on this move..." });

🎯 Custom Tools

Project includes custom tools:

1. Get Game State Tool

const getGameStateTool = {
  name: "get_game_state",
  description: "Get current game state and move history",
  parameters: { type: "object", properties: {} },
  handler: async () => ({
    currentFEN: getCurrentFEN(),
    moveCount: getMoveCount(),
    lastMoves: getLastMoves(5),
    gamePhase: determinePhase()
  })
};

2. Analyze Position Tool

const analyzePositionTool = {
  name: "analyze_position",
  description: "Analyze current board position",
  parameters: {
    type: "object",
    properties: {
      depth: { type: "number", description: "Analysis depth" }
    }
  },
  handler: async ({ depth = 3 }) => ({
    evaluation: calculateEval(),
    threats: identifyThreats(),
    suggestions: getSuggestions()
  })
};

🔒 Security & Best Practices

  1. Session Management: Automatic cleanup and session reuse
  2. Error Handling: Comprehensive error catching and user feedback
  3. Timeout Control: Prevent long-running operations
  4. Resource Cleanup: Proper cleanup of Copilot client resources
  5. Type Safety: Comprehensive TypeScript type definitions

📊 Performance Optimization

  • Streaming Response: Reduce time to first byte
  • 🔄 Session Reuse: Avoid repeated initialization
  • 📦 Code Splitting: Vite code splitting
  • 🎨 CSS Optimization: Use CSS variables and minimal styles

🛠️ Development Guide

Debug Mode

# Enable verbose logging
LOG_LEVEL=debug npm run dev:server

# View Copilot CLI output
COPILOT_CLI_ARGS=--verbose npm run dev:server

Build for Production

# Build frontend
npm run build

# Start production server
npm start

Type Checking

# Check TypeScript types
npm run type-check

🐛 Troubleshooting

Copilot CLI Not Found

# Check if CLI is installed
copilot --version

# Check PATH environment variable
echo $PATH | grep copilot

# Manually specify path
echo "COPILOT_CLI_PATH=/path/to/copilot" >> .env

Authentication Issues

# Re-login
copilot auth logout
copilot auth login

# Check auth status
copilot auth status

WebSocket Connection Failed

  • Ensure backend server is running
  • Check firewall settings
  • Verify port is not in use

📝 Environment Variables

Variable Default Description
PORT 3000 Backend server port
NODE_ENV development Runtime environment
COPILOT_CLI_PATH copilot CLI executable path
LOG_LEVEL info Logging level

🤝 Contributing

Contributions are welcome! Feel free to submit Pull Requests.

📄 License

MIT License - see LICENSE file for details

🙏 Acknowledgments

📞 Contact

For questions or suggestions, please submit an Issue.


Made with ❤️ for Chess and AI Enthusiasts

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published