# creem-store-agent

Adopt this skill: https://proskills.md/skills/other/malakhov-dmitrii-creem-store-agent

Page: https://proskills.md/skills/other/malakhov-dmitrii-creem-store-agent
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 1864
upstream: https://github.com/malakhov-dmitrii/creem-store-agent/blob/HEAD/SKILL.md

```text
---
name: creem-store-agent
description: "AI-powered Creem store monitor — alerts, churn analysis, autonomous actions via Telegram"
user-invocable: true
metadata:
  openclaw:
    emoji: "🍦"
    primaryEnv: CREEM_API_KEY
    requires:
      bins:
        - node
      env:
        - CREEM_API_KEY
        - CREEM_WEBHOOK_SECRET
        - TELEGRAM_BOT_TOKEN
        - TELEGRAM_CHAT_ID
        - ANTHROPIC_API_KEY
---

# Creem Store Agent

AI-powered monitoring for your Creem store. Sends real-time Telegram alerts for sales, subscriptions, disputes, and refunds. Uses Claude AI to analyze churn events and autonomously recommend retention actions.

## Commands

- `/creem-status` — Check store connection and webhook status
- `/creem-report` — Daily revenue summary (MRR, churn, new sales)

## Features

- **Real-time alerts**: Formatted Telegram notifications for all Creem events
- **AI churn analysis**: Claude Haiku analyzes cancellations and recommends retention actions
- **Autonomous actions**: Create retention discounts or pause subscriptions via inline buttons
- **Event deduplication**: Handles Creem webhook retries gracefully
- **HMAC verification**: Validates webhook signatures for security

## Setup

1. Install: `clawhub install creem-store-agent`
2. Set environment variables (see `.env.example`)
3. Expose webhook URL: `ngrok http 3000` (development)
4. Register webhook in Creem dashboard: `https://your-ngrok-url.ngrok.io/webhook/creem`

## Environment Variables

| Variable | Description |
|----------|-------------|
| `CREEM_API_KEY` | Creem API key (test: `creem_test_xxx`) |
| `CREEM_WEBHOOK_SECRET` | Webhook signing secret from Creem dashboard |
| `TELEGRAM_BOT_TOKEN` | Telegram bot token from @BotFather |
| `TELEGRAM_CHAT_ID` | Telegram chat ID for notifications |
| `ANTHROPIC_API_KEY` | Anthropic API key for Claude Haiku |
```

## File: README.md
upstream: https://github.com/malakhov-dmitrii/creem-store-agent/blob/HEAD/README.md

````text
# Creem Store Agent — OpenClaw Skill

[![Tests](https://img.shields.io/badge/tests-138%20passing-brightgreen)](https://github.com/malakhov-dmitrii/creem-store-agent) [![Coverage](https://img.shields.io/badge/coverage-84%25-green)](https://github.com/malakhov-dmitrii/creem-store-agent) [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue)](https://www.typescriptlang.org/) [![ClawHub](https://img.shields.io/badge/ClawHub-creem--store--agent-orange)](https://clawhub.ai/skills/creem-store-agent) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

AI-powered monitoring for your [Creem](https://creem.io) store. Sends real-time Telegram alerts for sales, subscriptions, disputes, and refunds. Uses Claude AI to analyze churn events and autonomously recommend retention actions — create discounts or pause subscriptions with one tap.

## Architecture

```
Creem Webhook POST
    │
    ▼
┌───────────────────────────────┐
│ OpenClaw Plugin HTTP Route    │
│ /webhook/creem                │
│ (IncomingMessage/ServerResponse)│
├───────────────────────────────┤
│ webhook-handler.ts            │
│ • HMAC-SHA256 verify          │
│ • Event deduplication         │
│ • JSON parse                  │
└───────────┬───────────────────┘
            │
            ▼
┌───────────────────────────────┐
│ event-processor.ts            │
│ • Classify event type         │
│ • Route: simple → rule-engine │
│ •        churn  → llm-analyzer│
└───────┬───────────┬───────────┘
        │           │
        ▼           ▼
┌──────────────┐ ┌──────────────────────┐
│ rule-engine  │ │ llm-analyzer.ts      │
│ • Format     │ │ • Fetch Creem context│
│   alert msg  │ │ • Claude Haiku call  │
└──────┬───────┘ │ • Parse JSON resp    │
       │         │ • Fallback to rules  │
       │         └──────────┬───────────┘
       │                    │
       ▼                    ▼
┌──────────────────────────────────────┐
│ telegram.ts                          │
│ • Send formatted alerts              │
│ • Inline buttons (Apply/Pause/Skip)  │
│ • /report, /status commands          │
└──────────────────┬───────────────────┘
                   │ user clicks button
                   ▼
┌──────────────────────────────────────┐
│ action-executor.ts                   │
│ • creem.discounts.create()           │
│ • creem.subscriptions.pause()        │
│ • Format result message              │
└──────────────────────────────────────┘
```

## Features

### Real-time Event Alerts

Handles all 13 Creem webhook events with formatted Telegram notifications:

| Event | Emoji | Urgency |
|-------|-------|---------|
| `checkout.completed` | 💰 | Low |
| `subscription.active` | 🎉 | Low |
| `subscription.paid` | 🔄 | Low |
| `subscription.canceled` | ❌ | **Churn** |
| `subscription.scheduled_cancel` | ⏰ | **Churn** |
| `subscription.unpaid` | 🚫 | Low |
| `subscription.past_due` | ⚠️ | **High** |
| `subscription.paused` | ⏸️ | Low |
| `subscription.expired` | 💀 | Medium |
| `subscription.trialing` | 🆓 | Low |
| `subscription.update` | 📝 | Low |
| `refund.created` | 💸 | Medium |
| `dispute.created` | 🚨 | **High** |

### AI Churn Analysis

When a cancellation event arrives, Claude Haiku analyzes the customer:

- **Customer tenure** and total revenue
- **Cancel reason** from webhook payload
- **Recommended action**: Create discount, pause subscription, or let go
- **Confidence score** (0-1) for autonomous execution

### Autonomous Actions

- **Auto-execute** when AI confidence ≥ 80%
- **Manual approval** via Telegram inline buttons when confidence is lower
- Actions: Apply retention discount, pause subscription, or skip

### Telegram Commands

- `/creem-status` — Check agent health and webhook status
- `/creem-report` — Revenue summary

## Demo

[![Demo Video](https://img.youtube.com/vi/LkCxjkBaDqQ/maxresdefault.jpg)](https://youtu.be/LkCxjkBaDqQ)

[Watch the demo](https://youtu.be/LkCxjkBaDqQ) | [Read the tutorial on dev.to](https://dev.to/hennessy811/building-an-ai-agent-that-saves-your-saas-revenue-nkf)

Run locally: `npm run demo:server` + `npm run demo` to see the full flow.

## Setup

### Prerequisites

- Node.js 20+
- [OpenClaw](https://openclaw.dev) installed and running
- Telegram bot (create via [@BotFather](https://t.me/BotFather))
- [Creem](https://creem.io) account with API key
- [Anthropic](https://console.anthropic.com) API key

### Installation

```bash
clawhub install creem-store-agent
```

Or manually:

```bash
git clone https://github.com/malakhov-dmitrii/creem-store-agent
```

Or via ClawHub:

```bash
clawhub install creem-store-agent
cd creem-store-agent
npm install
npm run build
```

### Environment Variables

Create a `.env` file (see `.env.example`):

| Variable | Description |
|----------|-------------|
| `CREEM_API_KEY` | Creem API key (test: `creem_test_xxx`) |
| `CREEM_WEBHOOK_SECRET` | Webhook signing secret from Creem dashboard |
| `TELEGRAM_BOT_TOKEN` | Telegram bot token from @BotFather |
| `TELEGRAM_CHAT_ID` | Telegram chat ID for notifications |
| `ANTHROPIC_API_KEY` | Anthropic API key for Claude Haiku |

### Webhook Setup

1. Start OpenClaw with the skill enabled
2. Expose your local server: `ngrok http 3000`
3. Register the webhook URL in your [Creem dashboard](https://creem.io/dashboard):
   ```
   https://your-ngrok-url.ngrok.io/webhook/creem
   ```
4. Select all events you want to monitor

### Test with Demo Script

```bash
npm run demo
```

This sends 5 sample webhook events (sale, subscription, cancellation, payment failure, dispute) to test the full flow.

## How It Works

1. **Creem sends a webhook** to `/webhook/creem`
2. **Signature verification** — HMAC-SHA256 with timing-safe comparison
3. **Deduplication** — event IDs tracked in memory to prevent duplicate processing
4. **Classification** — cancellations go through AI analysis; everything else gets a formatted alert
5. **AI Analysis** — Claude Haiku evaluates customer value, tenure, and cancel reason
6. **Action** — high-confidence decisions auto-execute; others await Telegram approval
7. **Execution** — creates retention discounts or pauses subscriptions via Creem SDK

### LLM Decision Logic

| Signal | Recommendation |
|--------|---------------|
| High tenure (>6 months) or high revenue (>$500) | CREATE_DISCOUNT (20-40%) |
| Medium tenure, medium value | SUGGEST_PAUSE |
| Low tenure (<2 months) or low value | NO_ACTION |

Fallback: If Claude API fails or returns unparseable response, rule-based logic takes over with confidence 0.5.

## Testing

```bash
npm test                # Run all 138 tests
npm run test:watch      # Watch mode
npm run test:coverage   # Coverage report
npm run typecheck       # TypeScript type checking
```

138 tests across 10 test files covering all modules.

## Tech Stack

- **Runtime**: Node.js 20+ / OpenClaw
- **Language**: TypeScript 5.7
- **AI**: Claude Haiku 4.5 via `@anthropic-ai/sdk`
- **Payments**: Creem SDK (`creem` npm package)
- **Notifications**: Telegram Bot API (`node-telegram-bot-api`)
- **Testing**: Vitest 3.x with V8 coverage
- **Webhook Security**: HMAC-SHA256 with `timingSafeEqual`

## Project Structure

```
src/
├── types.ts           # TypeScript interfaces
├── webhook-handler.ts # HMAC verification, dedup, body parsing
├── event-processor.ts # Event classification (simple vs churn)
├── rule-engine.ts     # Emoji, urgency, alert formatting
├── llm-analyzer.ts    # Claude Haiku churn analysis
├── action-executor.ts # Creem SDK actions (discount, pause)
├── telegram.ts        # Bot wrapper, alert formatting, keyboards
├── index-helpers.ts   # Pure functions extracted from index
└── index.ts           # Plugin entry point, wiring
tests/                 # Mirror of src/ with .test.ts files
demo/
└── demo-script.ts     # Sends sample webhooks for video recording
```

## License

MIT
````
