npm package: @openpets/posthog
Description: PostHog plugin for OpenCode - comprehensive analytics, feature flags, and event tracking
Latest version: 1.0.5

# PostHog Plugin for OpenCode

A comprehensive PostHog integration plugin for OpenCode that provides full access to PostHog's analytics, feature flags, event tracking, and insights capabilities through a factory-based architecture.

## Features

- **Event Tracking**: Capture single and batch events with custom properties
- **Feature Flags**: Create, manage, evaluate, and update feature flags
- **Analytics & Insights**: Get trends, insights, and analytics data
- **Person Management**: Track and update user/person properties
- **Session Recordings**: Access and query session recordings
- **Cohorts & Annotations**: Manage cohorts and create annotations
- **Project Management**: Get project information and configuration

## Prerequisites

- PostHog account (cloud or self-hosted)
- Personal API Key from PostHog
- Project API Key (for event capture)

## Setup

### 1. Get PostHog API Keys

#### Personal API Key:
1. Log into your PostHog instance
2. Go to Settings → Personal API Keys
3. Create a new Personal API Key
4. Copy the key

#### Project API Key:
1. Go to Project Settings
2. Find your Project API Key
3. Copy the key

### 2. Configure Environment

Create a `.env` file in the posthog plugin directory:

```bash
cp .env.example .env
```

Edit `.env` with your credentials:

```bash
POSTHOG_HOST=https://app.posthog.com
POSTHOG_API_KEY=phx_your_personal_api_key_here
POSTHOG_PROJECT_API_KEY=phc_your_project_api_key_here
```

For self-hosted PostHog, use your instance URL:
```bash
POSTHOG_HOST=https://posthog.yourdomain.com
```

### 3. Install Dependencies

```bash
npm install
```

### 4. Test Connection

```bash
opencode run "check posthog status"
```

## Using from Other Projects

Add to your project's `opencode.json`:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "plugin": [
    "/absolute/path/to/openpets/pets/posthog/index.ts"
  ]
}
```

## Available Tools

### Event Tracking

#### posthog-capture-event
Capture a single event with optional properties.

**Parameters:**
- `event` (required): Event name (e.g., "button_clicked", "page_viewed")
- `distinct_id` (required): Unique user/entity identifier
- `properties` (optional): Key-value pairs of event properties
- `timestamp` (optional): ISO timestamp (defaults to now)

**Examples:**
```bash
opencode run "capture event 'page_view' for user 'user_123'"
opencode run "capture event 'button_clicked' for user 'user_123' with properties {button_name: 'signup', page: '/home'}"
```

#### posthog-batch-capture-events
Capture multiple events in a single batch request for better performance.

**Parameters:**
- `events` (required): Array of event objects

**Example:**
```bash
opencode run "batch capture events: [{event: 'login', distinct_id: 'user_1'}, {event: 'view_dashboard', distinct_id: 'user_1'}]"
```

#### posthog-get-events
Retrieve events with optional filtering.

**Parameters:**
- `distinct_id` (optional): Filter by user ID
- `event` (optional): Filter by event name
- `limit` (optional): Max results (default: 100)
- `offset` (optional): Skip results (default: 0)

**Examples:**
```bash
opencode run "get events for user 'user_123'"
opencode run "get events with name 'page_view' limit 50"
```

### Person Management

#### posthog-get-person
Get information about a person by their distinct ID.

**Parameters:**
- `distinct_id` (required): The person's unique identifier

**Example:**
```bash
opencode run "get person 'user_123'"
```

#### posthog-update-person
Update or set properties for a person (identify operation).

**Parameters:**
- `distinct_id` (required): The person's unique identifier
- `properties` (required): Properties to set (e.g., {email: "user@example.com", name: "John"})

**Example:**
```bash
opencode run "update person 'user_123' with properties {email: 'john@example.com', name: 'John Doe', plan: 'premium'}"
```

### Feature Flags

#### posthog-list-feature-flags
List all feature flags in the project.

**Example:**
```bash
opencode run "list feature flags"
```

#### posthog-get-feature-flag
Get details of a specific feature flag by ID.

**Parameters:**
- `flag_id` (required): The feature flag ID

**Example:**
```bash
opencode run "get feature flag 123"
```

#### posthog-create-feature-flag
Create a new feature flag.

**Parameters:**
- `key` (required): Unique key for the flag
- `name` (required): Display name
- `filters` (required): Filter configuration
- `active` (optional): Whether flag is active (default: true)
- `rollout_percentage` (optional): Percentage rollout (0-100)

**Example:**
```bash
opencode run "create feature flag with key 'new-dashboard' and name 'New Dashboard UI'"
```

#### posthog-update-feature-flag
Update an existing feature flag.

**Parameters:**
- `flag_id` (required): The feature flag ID
- `key`, `name`, `filters`, `active`, `rollout_percentage` (optional): Fields to update

**Example:**
```bash
opencode run "update feature flag 123 set active to false"
```

#### posthog-delete-feature-flag
Delete a feature flag.

**Parameters:**
- `flag_id` (required): The feature flag ID to delete

**Example:**
```bash
opencode run "delete feature flag 123"
```

#### posthog-evaluate-feature-flag
Evaluate a feature flag for a specific user.

**Parameters:**
- `flag_key` (required): The feature flag key
- `distinct_id` (required): The user ID to evaluate for
- `person_properties` (optional): Person properties for evaluation

**Example:**
```bash
opencode run "evaluate feature flag 'new-dashboard' for user 'user_123'"
```

### Analytics & Insights

#### posthog-get-insights
Get insights/analytics data from PostHog.

**Parameters:**
- `events` (required): Array of events to analyze
- `date_from` (optional): Start date (default: "-7d")
- `date_to` (optional): End date (default: "now")
- `interval` (optional): Data interval (hour/day/week/month, default: day)

**Example:**
```bash
opencode run "get insights for events 'page_view' and 'button_click' from last 30 days"
```

#### posthog-get-trend
Get trend data for a specific event.

**Parameters:**
- `event_name` (required): Event name to get trends for
- `date_from` (optional): Start date (default: "-7d")
- `date_to` (optional): End date (default: "now")

**Example:**
```bash
opencode run "get trend for event 'signup' from last 30 days"
```

#### posthog-get-project-info
Get information about the current PostHog project.

**Example:**
```bash
opencode run "get project info"
```

### Session Recordings

#### posthog-get-session-recordings
Get session recordings from PostHog.

**Parameters:**
- `limit` (optional): Max recordings (default: 50)
- `offset` (optional): Skip recordings (default: 0)
- `date_from` (optional): Start date filter
- `date_to` (optional): End date filter

**Example:**
```bash
opencode run "get session recordings from last 7 days limit 10"
```

### Cohorts & Annotations

#### posthog-get-cohorts
Get all cohorts from PostHog.

**Example:**
```bash
opencode run "get cohorts"
```

#### posthog-get-annotations
Get all annotations from PostHog.

**Example:**
```bash
opencode run "get annotations"
```

#### posthog-create-annotation
Create a new annotation in PostHog.

**Parameters:**
- `content` (required): Annotation content/message
- `date_marker` (required): ISO date string for the annotation
- `scope` (optional): "organization" or "project" (default: "project")

**Example:**
```bash
opencode run "create annotation 'Deployed v2.0' for today"
```

### Status & Configuration

#### posthog-status
Check PostHog connection and configuration status.

**Example:**
```bash
opencode run "check posthog status"
```

## Common Use Cases

### Track User Journey
```bash
# 1. Identify user
opencode run "update person 'user_123' with properties {email: 'john@example.com', signup_date: '2024-01-15'}"

# 2. Track events
opencode run "capture event 'signed_up' for user 'user_123'"
opencode run "capture event 'completed_onboarding' for user 'user_123'"
opencode run "capture event 'first_purchase' for user 'user_123' with properties {amount: 49.99, product: 'premium_plan'}"

# 3. Check user data
opencode run "get person 'user_123'"
opencode run "get events for user 'user_123'"
```

### Feature Flag Workflow
```bash
# 1. Create feature flag
opencode run "create feature flag with key 'beta-ui' and name 'New Beta UI' with rollout 10"

# 2. Evaluate for user
opencode run "evaluate feature flag 'beta-ui' for user 'user_123'"

# 3. Gradually increase rollout
opencode run "update feature flag 456 set rollout_percentage to 50"

# 4. Monitor usage
opencode run "get trend for event 'beta_ui_viewed' from last 7 days"
```

### Analytics Dashboard
```bash
# 1. Get project overview
opencode run "get project info"

# 2. Get event trends
opencode run "get trend for event 'page_view' from last 30 days"
opencode run "get trend for event 'conversion' from last 30 days"

# 3. Get detailed insights
opencode run "get insights for events ['signup', 'purchase'] from last 30 days with interval week"

# 4. Add annotation for context
opencode run "create annotation 'Marketing campaign launched' for '2024-01-15'"
```

## Configuration

### Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `POSTHOG_HOST` | PostHog instance URL | Yes |
| `POSTHOG_API_KEY` | Personal API Key | Yes |
| `POSTHOG_PROJECT_API_KEY` | Project API Key | No* |

\* Required for event capture operations

### PostHog Cloud vs Self-Hosted

**Cloud (app.posthog.com):**
```bash
POSTHOG_HOST=https://app.posthog.com
```

**Self-Hosted:**
```bash
POSTHOG_HOST=https://posthog.yourdomain.com
```

**PostHog EU Cloud:**
```bash
POSTHOG_HOST=https://eu.posthog.com
```

## Error Handling

All tools return structured JSON responses with error information:

```json
{
  "success": false,
  "error": "Error message here",
  "metadata": {
    "timestamp": "2024-01-15T10:30:00Z"
  }
}
```

Common errors:
- **Authentication Failed**: Check your API keys
- **Project Not Found**: Verify POSTHOG_HOST and project access
- **Rate Limit**: PostHog has rate limits on API calls
- **Invalid Event**: Check event name and properties format

## API Reference

This plugin uses the PostHog REST API. For detailed API documentation, visit:
- [PostHog API Docs](https://posthog.com/docs/api)
- [Feature Flags API](https://posthog.com/docs/api/feature-flags)
- [Events API](https://posthog.com/docs/api/events)

## Development

### Testing

```bash
# Test basic connectivity
npm run quickstart

# Run all test queries
npm run test:queries

# Run scenario tests
npm run test:scenarios

# Run all tests
npm run test:all
```

### Adding New Features

1. Update the PostHog provider in `src/utils/posthog/index.ts`
2. Add new tool definitions in `pets/posthog/index.ts`
3. Update this README with documentation
4. Add test queries to `package.json`

## Architecture

This plugin follows the OpenCode factory-based architecture:

- **Provider Layer**: `src/utils/posthog/` - PostHog API client
- **Plugin Layer**: `pets/posthog/index.ts` - Tool definitions and orchestration
- **Factory Pattern**: Uses `createPlugin()` for consistent tool creation
- **Type Safety**: Zod schemas for parameter validation

## Troubleshooting

### Connection Issues
```bash
# Check status
opencode run "check posthog status"

# Verify environment variables
echo $POSTHOG_HOST
echo $POSTHOG_API_KEY
```

### Event Not Appearing
- Ensure `POSTHOG_PROJECT_API_KEY` is set
- Check event name doesn't contain special characters
- Verify the project has ingestion enabled

### Feature Flag Not Working
- Check flag is active in PostHog dashboard
- Verify user properties match flag filters
- Try evaluating flag through PostHog UI first

### Rate Limiting
- PostHog has rate limits (typically 1000 req/sec)
- Use batch operations when capturing multiple events
- Add delays between large operations

## Resources

- [PostHog Documentation](https://posthog.com/docs)
- [PostHog API Reference](https://posthog.com/docs/api)
- [OpenCode Plugin Documentation](https://opencode.ai/docs)

## License

MIT

## Support

For issues specific to this plugin:
- File an issue in the OpenPets repository

For PostHog-related questions:
- Visit [PostHog Community](https://posthog.com/questions)
- Check [PostHog Docs](https://posthog.com/docs)