Metadata-Version: 2.4
Name: prompt-collector
Version: 0.1.1
Summary: A CLI tool for collecting and forwarding AI prompts/responses to API / 收集和转发 AI Prompt 与响应的 CLI 工具
License: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx[socks]>=0.24.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
Requires-Dist: responses>=0.23.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"

# Prompt Collector

[![PyPI version](https://badge.fury.io/py/prompt-collector.svg)](https://pypi.org/project/prompt-collector/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

一个 CLI 工具，用于收集 Prompt 和 AI 响应，并推送到远程 API 服务。

## 功能特点

- 支持发送 `prompt` 和 `result` 两种类型的事件
- 从环境变量读取配置，支持静默失败
- 从 stdin 或命令行参数读取内容
- 内容自动截断（最大 10000 字符）
- 错误日志写入 `/tmp/prompt_collector_error.log`

## 安装

### 从 PyPI 安装（推荐）

```bash
# 使用 pip 安装
pip install prompt-collector

# 或使用 uv 安装
uv pip install prompt-collector
```

### 从源码安装

```bash
# 克隆仓库
git clone https://github.com/yourusername/prompt-collector.git
cd prompt-collector

# 安装依赖
pip install -e ".[dev]"

# 或使用生产依赖
pip install -e .
```

## 配置

通过环境变量配置：

```bash
export PROMPT_COLLECTOR_API_URL="https://your-api.com"  # API 基础 URL（必需）
export PROMPT_COLLECTOR_USERNAME="your-username"         # 用户名（必需）
export PROMPT_COLLECTOR_API_KEY="your-api-key"          # API Key（可选）
export PROMPT_COLLECTOR_TIMEOUT="5"                     # 超时时间，默认 5 秒（可选）
```

## 使用方法

### 基本用法

```bash
# 发送 Prompt（从 stdin 读取）
echo '{"session_id": "sess_abc123", "content": "Hello AI"}' | prompt-collector --type prompt

# 发送 Result（从 stdin 读取）
echo '{"session_id": "sess_abc123", "content": "AI response"}' | prompt-collector --type result

# 发送原始文本
printf "Hello AI" | prompt-collector --type prompt --session-id "sess_abc123"

# 使用命令行参数
prompt-collector --type prompt --session-id "sess_abc123" --content "Hello AI"
```

### 与 Claude Code 集成

Claude Code 支持通过 hooks 在特定事件触发时执行自定义命令。

#### 配置步骤

1. 在项目根目录或用户主目录创建 `.claude/settings.json`：

```bash
# 项目级配置（推荐）
mkdir -p .claude
touch .claude/settings.json

# 或全局配置
mkdir -p ~/.claude
touch ~/.claude/settings.json
```

2. 添加 hooks 配置：

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

#### 可用的 Claude Code 环境变量

| 变量名 | 说明 | 示例值 |
|--------|------|--------|
| `CLAUDE_SESSION_ID` | 当前会话唯一标识 | `abc123-def456` |
| `CLAUDE_LAST_MESSAGE` | 最后一条消息内容 | `"Hello AI"` |
| `CLAUDE_PROJECT_DIR` | 当前项目目录 | `/home/user/myproject` |

#### 可用的 Hooks 类型

| Hook 名称 | 触发时机 |
|-----------|----------|
| `UserPromptSubmit` | 用户提交消息时 |
| `Stop` | 会话结束或 AI 响应完成时 |

#### 完整配置示例

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

#### 验证配置

配置完成后，启动 Claude Code 并输入任意消息，检查数据是否被正确收集：

```bash
# 查看错误日志
tail -f /tmp/prompt_collector_error.log

# 测试配置是否正确加载
python -c "from prompt_collector.config import get_api_base_url; print(get_api_base_url())"
```

### 与 Cursor 集成

Cursor 支持加载 Claude Code 的 hooks 配置，实现无缝兼容。

#### 配置示例

在项目根目录创建 `.claude/settings.json`：

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

详细配置说明请参考 [Cursor 第三方 Hook 官方文档](https://cursor.com/cn/docs/agent/third-party-hooks)。

## CLI 参数

```
usage: prompt-collector [-h] --type {prompt,result} [--session-id SESSION_ID] [--content CONTENT]

options:
  -h, --help            show this help message and exit
  --type {prompt,result}
                        Type of event to send: 'prompt' for user input, 'result' for AI response
  --session-id SESSION_ID
                        Session identifier (can also be read from stdin JSON)
  --content CONTENT     Content to send (can also be read from stdin)
```

## API 接口

工具会向 `POST {API_URL}/api/sessions` 发送请求：

**Request:**
```json
{
  "username": "your-username",
  "session_id": "session-identifier",
  "prompt": "user prompt content (仅当 type=prompt)",
  "result": "ai response content (仅当 type=result)"
}
```

## 测试

```bash
# 运行所有测试
pytest

# 运行特定测试
pytest tests/test_parser.py

# 带覆盖率报告
pytest --cov=prompt_collector
```

## 错误排查

查看错误日志：
```bash
tail -f /tmp/prompt_collector_error.log
```

启用调试日志（取消 `main.py` 中 `debug_log()` 函数的注释）。

## 项目结构

```
prompt-collector/
├── pyproject.toml              # 项目配置
├── README.md                   # 项目说明
├── src/
│   └── prompt_collector/
│       ├── __init__.py
│       ├── __main__.py         # 模块入口
│       ├── config.py           # 环境变量配置
│       ├── parser.py           # 输入解析
│       ├── formatter.py        # 消息格式化
│       ├── sender.py           # HTTP 发送
│       └── main.py             # CLI 和主流程
└── tests/                      # 测试目录
```

---

# English Version

# Prompt Collector

[![PyPI version](https://badge.fury.io/py/prompt-collector.svg)](https://pypi.org/project/prompt-collector/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

A CLI tool for collecting prompts and AI responses, and pushing them to a remote API service.

## Features

- Supports sending `prompt` and `result` event types
- Reads configuration from environment variables with silent failure support
- Reads content from stdin or command line arguments
- Automatic content truncation (max 10000 characters)
- Error logs written to `/tmp/prompt_collector_error.log`

## Installation

### Install from PyPI (Recommended)

```bash
# Using pip
pip install prompt-collector

# Or using uv
uv pip install prompt-collector
```

### Install from Source

```bash
# Clone the repository
git clone https://github.com/yourusername/prompt-collector.git
cd prompt-collector

# Install dependencies
pip install -e ".[dev]"

# Or install production dependencies only
pip install -e .
```

## Configuration

Configure via environment variables:

```bash
export PROMPT_COLLECTOR_API_URL="https://your-api.com"  # API base URL (required)
export PROMPT_COLLECTOR_USERNAME="your-username"         # Username (required)
export PROMPT_COLLECTOR_API_KEY="your-api-key"          # API Key (optional)
export PROMPT_COLLECTOR_TIMEOUT="5"                     # Timeout in seconds, default 5 (optional)
```

## Usage

### Basic Usage

```bash
# Send Prompt (read from stdin)
echo '{"session_id": "sess_abc123", "content": "Hello AI"}' | prompt-collector --type prompt

# Send Result (read from stdin)
echo '{"session_id": "sess_abc123", "content": "AI response"}' | prompt-collector --type result

# Send raw text
printf "Hello AI" | prompt-collector --type prompt --session-id "sess_abc123"

# Using command line arguments
prompt-collector --type prompt --session-id "sess_abc123" --content "Hello AI"
```

### Integration with Claude Code

Claude Code supports executing custom commands when specific events are triggered through hooks.

#### Configuration Steps

1. Create `.claude/settings.json` in the project root or user home directory:

```bash
# Project-level configuration (recommended)
mkdir -p .claude
touch .claude/settings.json

# Or global configuration
mkdir -p ~/.claude
touch ~/.claude/settings.json
```

2. Add hooks configuration:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

#### Available Claude Code Environment Variables

| Variable Name | Description | Example Value |
|---------------|-------------|---------------|
| `CLAUDE_SESSION_ID` | Unique session identifier | `abc123-def456` |
| `CLAUDE_LAST_MESSAGE` | Content of the last message | `"Hello AI"` |
| `CLAUDE_PROJECT_DIR` | Current project directory | `/home/user/myproject` |

#### Available Hook Types

| Hook Name | Trigger Timing |
|-----------|----------------|
| `UserPromptSubmit` | When user submits a message |
| `Stop` | When session ends or AI response completes |

#### Complete Configuration Example

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

#### Verify Configuration

After configuration, start Claude Code and type any message to check if data is being collected correctly:

```bash
# View error logs
tail -f /tmp/prompt_collector_error.log

# Test if configuration is loaded correctly
python -c "from prompt_collector.config import get_api_base_url; print(get_api_base_url())"
```

### Integration with Cursor

Cursor supports loading Claude Code hooks configuration for seamless compatibility.

#### Configuration Example

Create `.claude/settings.json` in the project root:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type prompt"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "prompt-collector --type result"
          }
        ]
      }
    ]
  }
}
```

For detailed configuration instructions, please refer to the [Cursor Third-Party Hooks Documentation](https://cursor.com/cn/docs/agent/third-party-hooks).

## CLI Parameters

```
usage: prompt-collector [-h] --type {prompt,result} [--session-id SESSION_ID] [--content CONTENT]

options:
  -h, --help            show this help message and exit
  --type {prompt,result}
                        Type of event to send: 'prompt' for user input, 'result' for AI response
  --session-id SESSION_ID
                        Session identifier (can also be read from stdin JSON)
  --content CONTENT     Content to send (can also be read from stdin)
```

## API Interface

The tool sends requests to `POST {API_URL}/api/sessions`:

**Request:**
```json
{
  "username": "your-username",
  "session_id": "session-identifier",
  "prompt": "user prompt content (only when type=prompt)",
  "result": "ai response content (only when type=result)"
}
```

## Testing

```bash
# Run all tests
pytest

# Run specific test
pytest tests/test_parser.py

# With coverage report
pytest --cov=prompt_collector
```

## Troubleshooting

View error logs:
```bash
tail -f /tmp/prompt_collector_error.log
```

Enable debug logs (uncomment the `debug_log()` function in `main.py`).

## Project Structure

```
prompt-collector/
├── pyproject.toml              # Project configuration
├── README.md                   # Project documentation
├── src/
│   └── prompt_collector/
│       ├── __init__.py
│       ├── __main__.py         # Module entry point
│       ├── config.py           # Environment variable configuration
│       ├── parser.py           # Input parsing
│       ├── formatter.py        # Message formatting
│       ├── sender.py           # HTTP sending
│       └── main.py             # CLI and main workflow
└── tests/                      # Test directory
```
