# Development Guide

This guide covers setting up your development environment and contributing to the Z.AI VS Code extension.

## Prerequisites

- Node.js 20.x or higher
- Visual Studio Code 1.104.0 or higher
- Git
- A Z.AI API key for testing

## Setup

1. **Clone the repository**
   ```bash
   git clone https://github.com/yourusername/zai-vscode-extension
   cd zai-vscode-extension
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Compile TypeScript**
   ```bash
   npm run compile
   ```

## Development Workflow

### Running the Extension

1. Open the project in VS Code
2. Press `F5` to start debugging
3. A new "Extension Development Host" window will open
4. Test the extension in this window

### Watch Mode

For automatic recompilation on file changes:
```bash
npm run watch
```

### Linting

Run ESLint to check code quality:
```bash
npm run lint
```

### Testing

Run the test suite:
```bash
npm test
```

## Project Structure

```
zai-vscode-extension/
├── src/
│   ├── extension.ts       # Extension entry point
│   ├── provider.ts        # Language model provider implementation
│   ├── apiClient.ts       # Z.AI API client with streaming
│   ├── apiKeyManager.ts   # Secure credential management
│   └── models.ts          # Model configurations
├── package.json           # Extension manifest
├── tsconfig.json          # TypeScript configuration
└── README.md             # User documentation
```

## Key Components

### Extension Activation (`extension.ts`)

The main entry point that:
- Registers the language model provider
- Sets up commands for API key management
- Shows welcome message on first run

### Provider (`provider.ts`)

Implements the `LanguageModelChatProvider` interface:
- `provideLanguageModelChatInformation`: Returns available models
- `provideLanguageModelChatResponse`: Handles chat requests
- `provideTokenCount`: Estimates token usage

### API Client (`apiClient.ts`)

Handles communication with Z.AI:
- Converts VS Code message format to Z.AI format
- Streams responses back to VS Code
- Handles tool calling and thinking mode
- Manages timeouts and cancellation

### API Key Manager (`apiKeyManager.ts`)

Manages secure credential storage:
- Uses VS Code's secret storage API
- Provides methods to get/set/clear API keys

## Making Changes

### Adding a New Model

1. Update `src/models.ts` with the new model configuration
2. Ensure the model ID matches Z.AI's API
3. Set appropriate context windows and capabilities
4. Update README.md with model details

### Modifying API Client

When changing API interactions:
1. Review Z.AI API documentation
2. Update type definitions if needed
3. Test streaming behavior thoroughly
4. Handle new error cases

### Adding Configuration Options

1. Add the setting to `package.json` under `contributes.configuration`
2. Read the setting in the appropriate module using `vscode.workspace.getConfiguration('zai')`
3. Document the setting in README.md

## Testing

### Manual Testing Checklist

- [ ] Extension activates without errors
- [ ] API key can be set and cleared
- [ ] Models appear in the model picker
- [ ] Chat responses stream correctly
- [ ] Tool calling works as expected
- [ ] Thinking mode can be toggled
- [ ] Error messages are clear and helpful
- [ ] Cancellation works properly
- [ ] Extension deactivates cleanly

### Testing with Different Scenarios

1. **No API Key**: Verify user is prompted appropriately
2. **Invalid API Key**: Check error handling and user guidance
3. **Network Issues**: Test timeout and error messages
4. **Long Conversations**: Verify token counting and context handling
5. **Tool Calling**: Test with various tool configurations

## Debugging

### Console Logging

Use `console.log()` and `console.error()` for debugging. Logs appear in:
- **Extension Host**: Developer Tools > Console
- **Extension Development Host**: Help > Toggle Developer Tools > Console

### Breakpoints

Set breakpoints in TypeScript files and use F5 to start debugging with breakpoints active.

### Common Issues

**Models not appearing**: 
- Check API key is valid
- Verify `provideLanguageModelChatInformation` is called
- Look for errors in console

**Streaming not working**:
- Check API endpoint configuration
- Verify response format matches expected structure
- Review stream processing logic

## Building for Release

### Create VSIX Package

```bash
npm install -g @vscode/vsce
vsce package
```

This creates a `.vsix` file you can:
- Install locally: `code --install-extension zai-language-models-0.1.0.vsix`
- Publish to marketplace (see Publishing section)

### Pre-publish Checklist

- [ ] Update version in `package.json`
- [ ] Update CHANGELOG.md
- [ ] Test in clean environment
- [ ] Verify all assets are included
- [ ] Check .vscodeignore excludes dev files
- [ ] Run full test suite
- [ ] Test the packaged .vsix

## Publishing

### To VS Code Marketplace

1. **Get Publisher Account**
   - Create account at [Visual Studio Marketplace](https://marketplace.visualstudio.com/)
   - Generate Personal Access Token

2. **Login to vsce**
   ```bash
   vsce login <publisher-name>
   ```

3. **Publish**
   ```bash
   vsce publish
   ```

### Version Bumping

```bash
# Patch version (0.1.0 -> 0.1.1)
vsce publish patch

# Minor version (0.1.0 -> 0.2.0)
vsce publish minor

# Major version (0.1.0 -> 1.0.0)
vsce publish major
```

## Contributing Guidelines

### Code Style

- Follow TypeScript best practices
- Use meaningful variable names
- Add comments for complex logic
- Keep functions focused and small

### Commit Messages

Use conventional commit format:
- `feat: add support for new model`
- `fix: resolve streaming issue`
- `docs: update README`
- `refactor: simplify API client`

### Pull Request Process

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Test thoroughly
5. Commit with clear messages
6. Push to your fork
7. Open a Pull Request

### Code Review

PRs should:
- Have a clear description of changes
- Include tests if applicable
- Update documentation
- Pass CI checks
- Be reviewed by at least one maintainer

## Resources

- [VS Code Extension API](https://code.visualstudio.com/api)
- [Language Model Chat Provider API](https://code.visualstudio.com/api/extension-guides/ai/language-model-chat-provider)
- [Z.AI API Documentation](https://docs.z.ai)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)

## Getting Help

- Open an issue for bugs or feature requests
- Join Z.AI Discord for API-related questions
- Check existing issues before creating new ones

## License

This project is licensed under the MIT License - see LICENSE file for details.
