Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"permissions": {
"allow": [
"Bash(npm run build:*)",
"Bash(mkdir:*)",
"Bash(cp:*)",
"Bash(npm install:*)",
"Bash(rm:*)",
"Bash(ls:*)",
"Bash(grep:*)",
"Bash(curl:*)",
"Bash(git -C /Users/johndpope/Documents/GitHub/atlas-ai-conversations-hub diff package.json)",
"Bash(git -C /Users/johndpope/Documents/GitHub/atlas-ai-conversations-hub diff vite.config.ts)",
"Bash(git -C /Users/johndpope/Documents/GitHub/atlas-ai-conversations-hub status)"
],
"deny": []
}
}
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
node_modules/
dist/
.env
grok-cookies.json
grok-cookies.json
.chrome-data/
.vscode/
104 changes: 104 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is a TypeScript client library for interacting with Grok AI (`grok-api-ts`). The library provides automated login functionality, cookie management, and comprehensive interaction with Grok's API including streaming responses.

## Common Commands

**Build the project:**
```bash
npm run build
# or
pnpm run build
```

**Development (run with ts-node):**
```bash
npm run dev
# or
pnpm run dev
```

**Clean build artifacts:**
```bash
npm run clean
# or
pnpm run clean
```

**Run example:**
```bash
npm run example
# or
pnpm run example
```

**Prepare for publishing:**
```bash
npm run prepublishOnly
# or
pnpm run prepublishOnly
```

## Architecture

### Core Components

- **`src/grokApi.ts`**: Main GrokAPI class containing all functionality
- **`src/index.ts`**: Entry point that exports the GrokAPI class and types
- **`examples/`**: Example usage files showing different API patterns

### Key Features

1. **Authentication System**: Uses patchright (patched Playwright) to automate browser-based login to X.AI
2. **Cookie Management**: Persistent cookie storage in `grok-cookies.json` to avoid repeated logins
3. **Streaming Support**: Real-time response streaming with token-by-token callbacks
4. **Conversation Management**: Maintains conversation state and supports follow-up messages

### Main API Methods

- `login(username, password)`: Automated browser login
- `sendMessage(options)`: Send message to Grok with customizable options
- `continueConversation(message)`: Continue existing conversation
- `sendMessageStream(options, callbacks)`: Streaming version with real-time callbacks
- `ensureAuthenticated()`: Checks/handles authentication state

### Key Data Structures

- `GrokSendMessageOptions`: Message configuration including search, image generation, custom instructions
- `ParsedGrokResponse`: Parsed response containing message, metadata, and conversation info
- `GrokStreamCallbacks`: Streaming callbacks for tokens, completion, and errors

## Dependencies

- **Runtime**: `got-scraping`, `patchright`, `tough-cookie`
- **Development**: TypeScript, ts-node, rimraf, puppeteer
- **Peer**: `chrome-launcher` (optional)

## Testing

Currently no test suite is configured (`"test": "echo \"No tests yet\"`). When implementing tests, consider testing:
- Authentication flow
- Message sending/receiving
- Cookie persistence
- Error handling
- Streaming functionality

## File Structure

- `src/`: TypeScript source files
- `dist/`: Compiled JavaScript output
- `examples/`: Usage examples
- `node_modules/`: Dependencies
- `.chrome-data/`: Browser profile data for authentication

## Important Notes

- Chrome browser is required for authentication (uses patchright)
- Cookies are stored in `grok-cookies.json` for persistence
- The library targets Node.js 14+ with ES2020
- Uses CommonJS modules for compatibility
- Includes TypeScript declarations for full type safety
164 changes: 164 additions & 0 deletions README-mock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Mock Grok API Server

This project includes a mock server that simulates the Grok API endpoints for development and testing purposes. The mock server eliminates the need for authentication and provides realistic streaming responses.

## Quick Start

1. **Install dependencies:**
```bash
npm install
# or
pnpm install
```

2. **Start the mock server:**
```bash
npm run mock-server
# or
pnpm run mock-server
```

3. **Run the mock example:**
```bash
# In another terminal
npm run mock-example
# or
pnpm run mock-example
```

## Mock Server Features

- **No Authentication Required**: Skip the complex browser-based login process
- **Realistic Streaming**: Simulates token-by-token response streaming
- **Conversation Management**: Maintains conversation state like the real API
- **Follow-up Suggestions**: Provides mock follow-up suggestions
- **Error Handling**: Proper error responses and status codes
- **CORS Support**: Configured for cross-origin requests

## Usage

### Using MockGrokAPI Class

```typescript
import { MockGrokAPI } from 'grok-api-ts';

const mockGrokApi = new MockGrokAPI('http://localhost:3001', true);

// Check if mock server is running
const isRunning = await mockGrokApi.checkMockServer();

// Send message (no authentication needed)
const response = await mockGrokApi.sendMessage({
message: "Hello, mock Grok!"
});

console.log(response.fullMessage);
```

### Direct API Calls

You can also make direct HTTP requests to the mock server:

```bash
# New conversation
curl -X POST http://localhost:3001/rest/app-chat/conversations/new \
-H "Content-Type: application/json" \
-d '{"message": "Hello!", "modelName": "grok-3"}'

# Continue conversation
curl -X POST http://localhost:3001/rest/app-chat/conversations/conv_1/responses \
-H "Content-Type: application/json" \
-d '{"message": "Follow up", "parentResponseId": "resp_1"}'

# Health check
curl http://localhost:3001/health
```

## Mock Server Endpoints

- `POST /rest/app-chat/conversations/new` - Create new conversation
- `POST /rest/app-chat/conversations/:id/responses` - Continue conversation
- `GET /health` - Health check endpoint

## Configuration

The mock server runs on port 3001 by default. You can customize the port:

```bash
PORT=3002 npm run mock-server
```

When using MockGrokAPI, specify the custom URL:

```typescript
const mockGrokApi = new MockGrokAPI('http://localhost:3002', true);
```

## Mock Response Format

The mock server returns responses in the same format as the real Grok API:

```json
{
"result": {
"conversation": {
"conversationId": "conv_1",
"title": "Mock Conversation 1"
},
"response": {
"token": "Hello ",
"responseId": "resp_1"
},
"finalMetadata": {
"followUpSuggestions": ["Follow up 1", "Follow up 2"],
"feedbackLabels": ["helpful", "accurate"]
}
}
}
```

## Development Benefits

1. **Faster Development**: No need to wait for real API authentication
2. **Offline Testing**: Work without internet connection
3. **Predictable Responses**: Consistent mock responses for testing
4. **Rate Limit Free**: No API rate limits during development
5. **Easy Debugging**: Full control over response timing and content

## Switching Between Real and Mock APIs

```typescript
// For development/testing
const grokApi = new MockGrokAPI('http://localhost:3001', true);

// For production
const grokApi = new GrokAPI();
await grokApi.login('username', 'password');
```

## Custom Mock Responses

You can modify `mock-server/server.ts` to customize:

- Response content and variety
- Streaming timing and behavior
- Error simulation
- Follow-up suggestions
- Conversation titles

## Troubleshooting

**Mock server won't start:**
- Check if port 3001 is available
- Install dependencies: `npm install`
- Check for TypeScript compilation errors

**Connection refused errors:**
- Ensure mock server is running: `npm run mock-server`
- Verify the correct port and URL
- Check firewall settings

**Streaming not working:**
- Ensure you're using the streaming methods correctly
- Check console for error messages
- Verify callback functions are properly defined
Loading