npm package: @nicotordev/prompt-enhancer-hook
Description: Claude Code hook that enhances user prompts using OpenAI GPT models with prompt engineering best practices
Author: NicoTorDev
Latest version: 1.0.0

# 🚀 Prompt Enhancer Hook

[![npm version](https://badge.fury.io/js/@nicotordev%2Fprompt-enhancer-hook.svg)](https://www.npmjs.com/package/@nicotordev/prompt-enhancer-hook)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Bun](https://img.shields.io/badge/Bun-000000?logo=bun&logoColor=white)](https://bun.sh/)

> Automatically enhance your Claude Code prompts with AI-powered prompt engineering best practices

**Author:** NicoTorDev, Concepción, Chile
**Date:** 10-10-2025
**TypeScript:** ❤️

---

## 📋 Table of Contents

- [Overview](#-overview)
- [Features](#-features)
- [Installation](#-installation)
- [Configuration](#-configuration)
- [Usage](#-usage)
- [How It Works](#-how-it-works)
- [Prompt Engineering Principles](#-prompt-engineering-principles)
- [Troubleshooting](#-troubleshooting)
- [Development](#-development)
- [License](#-license)

---

## 🎯 Overview

This Claude Code hook intercepts user prompts and enhances them using OpenAI's GPT models before sending them to Claude AI. It applies professional prompt engineering techniques to improve clarity, specificity, and structure.

**Before:**
```
"Fix the bug in my code"
```

**After (Enhanced):**
```
"Act as an experienced software engineer. Analyze the provided code to identify and fix the bug.

Please:
1. First, explain what the bug is and why it occurs
2. Provide the corrected code with inline comments
3. Suggest how to prevent similar bugs in the future

Format your response with clear sections for diagnosis, solution, and prevention."
```

---

## ✨ Features

- **🧠 Intelligent Enhancement** - Adds clarity, context, and structure to prompts
- **🔄 Model Fallback** - Automatically tries gpt-4o → gpt-4-turbo → gpt-4 → gpt-3.5-turbo
- **⚡ Fast** - Built with Bun for near-instant execution
- **🛡️ Robust** - Graceful error handling, never breaks your workflow
- **🎛️ Configurable** - Customize model, timeout, and debug settings
- **📝 Type-Safe** - Full TypeScript support with OpenAI SDK types

---

## 📦 Installation

### Method 1: Install from npm (Recommended)

```bash
# Install globally
npm install -g @nicotordev/prompt-enhancer-hook

# Or install locally in your Claude Code hooks directory
cd ~/.claude/_hooks
mkdir promptEnhancer
cd promptEnhancer
npm install @nicotordev/prompt-enhancer-hook
```

After installation:
1. Copy the `.env.example` to `.env`
2. Add your OpenAI API key to `.env`
3. Configure Claude Code hook (see [Usage](#-usage))

### Method 2: Install from source

#### Prerequisites

- [Bun](https://bun.sh/) v1.3.0 or higher
- [Claude Code](https://claude.com/claude-code) CLI
- OpenAI API key ([Get one here](https://platform.openai.com/api-keys))

#### Setup Steps

1. **Clone the repository:**
   ```bash
   git clone https://github.com/nicotordev/prompt-enhancer-hook.git
   cd prompt-enhancer-hook
   ```

2. **Install dependencies:**
   ```bash
   bun install
   ```

3. **Configure environment variables:**
   ```bash
   cp .env.example .env
   ```

4. **Edit `.env` and add your OpenAI API key:**
   ```bash
   OPENAI_API_KEY=sk-your-actual-api-key-here
   ```

5. **Make the script executable (if needed):**
   ```bash
   chmod +x index.ts
   ```

6. **Test the hook manually:**
   ```bash
   echo '{"text":"Fix the bug"}' | bun index.ts
   ```

---

## ⚙️ Configuration

### Environment Variables

Create a `.env` file with the following variables:

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `OPENAI_API_KEY` | ✅ Yes | - | Your OpenAI API key |
| `OPENAI_MODEL` | ❌ No | `gpt-4o` | Primary model to use |
| `OPENAI_TIMEOUT` | ❌ No | `10000` | Request timeout (milliseconds) |
| `DEBUG` | ❌ No | `false` | Enable debug logging (`true`/`1`) |

### Example `.env`

```bash
# Required
OPENAI_API_KEY=sk-proj-abc123...

# Optional
OPENAI_MODEL=gpt-4o
OPENAI_TIMEOUT=10000
DEBUG=false
```

---

## 🎮 Usage

### Registering with Claude Code

Add this hook to your Claude Code configuration:

```json
{
  "hooks": {
    "UserPromptSubmit": {
      "command": "bun /home/nicotordev/.claude/_hooks/promptEnhancer/index.ts"
    }
  }
}
```

### Testing Manually

You can test the hook by piping JSON to it:

```bash
# Basic test
echo '{"text":"Help me debug this"}' | bun index.ts

# With debug logging
DEBUG=true echo '{"text":"Explain recursion"}' | bun index.ts
```

### Expected Behavior

- **Success (exit 0):** Enhanced prompt sent to Claude via stdout
- **No API key (exit 0):** Original prompt passes through unchanged
- **Error (exit 0):** Original prompt passes through with error logged to stderr
- **Fatal error (exit 1):** Hook failed completely (rare)

---

## 🔍 How It Works

```mermaid
graph LR
    A[User Types Prompt] --> B[Claude Code Hook]
    B --> C[Read stdin JSON]
    C --> D[OpenAI API]
    D --> E[Enhanced Prompt]
    E --> F[Claude AI]
    F --> G[Response]
```

1. **Input:** Claude Code sends user prompt as JSON via stdin
2. **Enhancement:** Hook sends prompt to OpenAI with meta-prompt
3. **Meta-Prompt:** System prompt instructs GPT on enhancement best practices
4. **Output:** Enhanced prompt returned via stdout with exit code 0
5. **Fallback:** On any error, original prompt passes through unchanged

---

## 📚 Prompt Engineering Principles

The enhancement system applies these professional techniques:

### 1. **Clarity & Specificity**
- Transforms vague requests into precise, actionable instructions
- Adds concrete details about desired outcomes
- Uses specific terminology and clear language

### 2. **Context & Detail**
- Assigns appropriate roles (e.g., "Act as a senior developer")
- Specifies target audience when relevant
- Includes constraints (format, length, style)
- Provides necessary background

### 3. **Logical Structure**
- Organizes prompts: Context → Task → Output Format
- Breaks complex tasks into sequential steps
- Uses clear formatting (lists, sections, hierarchies)

### 4. **Positive Instructions**
- Focuses on what TO do, not what NOT to do
- Uses affirmative, constructive language
- Makes expectations explicit

### 5. **Task Decomposition**
- Breaks complex requests into manageable subtasks
- Creates clear hierarchies for multi-step processes
- Makes implicit requirements explicit

---

## 🐛 Troubleshooting

### Hook doesn't enhance prompts

**Check:**
1. Is `OPENAI_API_KEY` set in `.env`?
2. Does your API key have credits?
3. Is the `.env` file in the same directory as `index.ts`?

**Test:**
```bash
cd /home/nicotordev/.claude/_hooks/promptEnhancer
DEBUG=true echo '{"text":"test"}' | bun index.ts 2>&1 | grep -i error
```

### "No content in OpenAI response"

**Cause:** Model returned empty response
**Solution:** Check your OpenAI account status and API limits

### Timeout errors

**Cause:** Request took longer than configured timeout
**Solution:** Increase timeout in `.env`:
```bash
OPENAI_TIMEOUT=20000  # 20 seconds
```

### Invalid JSON errors

**Cause:** Hook receiving malformed input
**Solution:** Ensure Claude Code is sending valid JSON. Enable debug:
```bash
DEBUG=true
```

---

## 🛠️ Development

### Project Structure

```
promptEnhancer/
├── index.ts          # Main hook implementation
├── package.json      # Dependencies and metadata
├── tsconfig.json     # TypeScript configuration
├── .env.example      # Environment template
├── .env              # Your config (gitignored)
├── CLAUDE.md         # Project documentation
├── README.md         # This file
└── node_modules/     # Dependencies
```

### Running Tests

```bash
# Run tests (when implemented)
bun test

# Test with sample input
echo '{"text":"Hello"}' | bun index.ts

# Debug mode
DEBUG=true echo '{"text":"Hello"}' | bun index.ts 2>&1
```

### Building

Bun executes TypeScript directly, no build step needed!

```bash
bun index.ts
```

### Code Quality

- **TypeScript:** Strict mode enabled
- **Linting:** Follow standard TypeScript conventions
- **Error handling:** All errors caught and logged to stderr
- **Logging:** Use `logDebug()` and `logError()` helpers

---

## 📝 Exit Codes

| Code | Meaning | Behavior |
|------|---------|----------|
| `0` | Success or pass-through | Enhanced/original prompt sent to Claude via stdout |
| `1` | Fatal error | Hook failed (rare, check logs) |
| `2` | Block processing | Not used (would block prompt from reaching Claude) |

---

## 🤝 Contributing

This is a personal project by NicoTorDev. Feel free to fork and adapt for your needs!

---

## 📄 License

MIT License - Feel free to use and modify as needed.

---

## 🙏 Acknowledgments

- Built with [Bun](https://bun.sh/) - The fast all-in-one JavaScript runtime
- Powered by [OpenAI](https://openai.com/) - GPT models for enhancement
- Designed for [Claude Code](https://claude.com/claude-code) - Anthropic's CLI

---

## 📧 Contact

**Author:** NicoTorDev
**Location:** Concepción, Chile
**Love:** TypeScript ❤️

---

**Made with ❤️ and TypeScript on 10-10-2025**