Shell
Add Reddit Research Agent with production features
eddiebe14797b27a03e52f
diff --git a/agents/reddit-research/.gitignore b/agents/reddit-research/.gitignorenew file mode 100644index 0000000..5dc296b--- /dev/null+++ b/agents/reddit-research/.gitignore@@ -0,0 +1,31 @@+# Dependencies+node_modules/++# Build output+dist/++# Database+*.db++# Environment+.env+.env.local++# OS files+.DS_Store++# IDE+.vscode/+.idea/++# Logs+*.log++# Test output+coverage/++# Generated data files+*.json+!package.json+!package-lock.json+!tsconfig.jsondiff --git a/agents/reddit-research/README.md b/agents/reddit-research/README.mdnew file mode 100644index 0000000..821a4fb--- /dev/null+++ b/agents/reddit-research/README.md@@ -0,0 +1,239 @@+# π Reddit Research Agent++**Extract market research gold from Reddit using the hidden JSON API.**++An autonomous agent that discovers pain points, product opportunities, competitor mentions, and buying signals from Reddit discussions.++## The Hidden Trick++Add `/.json` to any Reddit URL:++```+https://www.reddit.com/r/SaaS/comments/xyz/title/+ β+https://www.reddit.com/r/SaaS/comments/xyz/title/.json+```++You get the **entire thread** including all nested comments as structured JSON. No API key required.++## Quick Start++```bash+# Install dependencies+npm install++# Set Claude API key (for analysis)+export ANTHROPIC_API_KEY=sk-ant-...++# Run a scan+npx tsx src/agent/index.ts run+```++## What You Get++### Pain Points+- Problems people are experiencing+- Frustrations with current solutions+- What's missing from the market++### Product Opportunities+- Features people wish existed+- Gaps competitors aren't filling+- Ideas with validation built-in++### Competitor Intelligence+- Products mentioned (positive/negative)+- Why people switch+- Pricing sensitivity++### Buying Signals+- "Looking for recommendations..."+- "Just switched from X to Y..."+- "Would pay for something that..."++## Usage++### Python Scripts (Quick Research)++```bash+# Find goldmine threads in a subreddit+python3 find_goldmine_threads.py SaaS+python3 find_goldmine_threads.py entrepreneur --query "frustrating"++# Extract a specific thread+python3 reddit_extractor.py "https://reddit.com/r/SaaS/comments/xyz/"+```++### TypeScript Agent (Automated Research)++```bash+# Single scan cycle+npx tsx src/agent/index.ts run++# Scheduled agent (daily at 9 AM)+npx tsx src/agent/index.ts schedule++# Add subreddits to track+npx tsx src/agent/index.ts add SaaS "wish existed"+npx tsx src/agent/index.ts add smallbusiness++# View statistics+npx tsx src/agent/index.ts stats++# Web dashboard to explore insights+npx tsx src/agent/index.ts dashboard 3456++# Parallel scan multiple subreddits+npx tsx src/agent/index.ts parallel "SaaS,entrepreneur,smallbusiness"+```++## Example Output++```+π TOP GOLDMINE THREADS+======================================================================++1. [Score: 39.7] I Took Over a Commercial Gym and it's Been a Nightmare+ π 1336 pts | π¬ 292 comments | π 97%+ π https://reddit.com/r/smallbusiness/comments/...++2. [Score: 36.76] We're getting crushed by the big bakery chains+ π 358 pts | π¬ 254 comments | π 96%+ π https://reddit.com/r/smallbusiness/comments/...+```++### Analyzed Insights++```+## Pain Points+- Manual order processing eating admin time (frequency: 5)+- Can't afford custom software development+- Competing on price is a losing battle++## Opportunities+- [high] Shopify-style ordering for wholesale bakeries+- [medium] Baker-specific software suite+- [high] Community engagement tools for local businesses++## Key Quote+> "If not, I will 100% create a plug-n-play baker software suite+> for free and sell it to other bakers for profit."+```++## High-Value Subreddits++| Category | Subreddits |+|----------|------------|+| **B2B/SaaS** | r/SaaS, r/startups, r/entrepreneur |+| **Small Business** | r/smallbusiness, r/Entrepreneur |+| **Dev Tools** | r/webdev, r/programming, r/devops |+| **Consumer** | r/productivity, r/ADHD, r/homelab |+| **Niche Hobbies** | Any passionate community |++## Goldmine Queries++The agent automatically searches for high-value phrases:++- `"wish existed"` - Product ideas with built-in demand+- `"hate about"` - Pain points and frustrations+- `"frustrating"` - Problems to solve+- `"looking for"` - Active buying intent+- `"alternative to"` - Competitor weakness+- `"switched from"` - Migration patterns+- `"paying for"` - Willingness to spend++## Architecture++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β Reddit Research Agent β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β Scanner βββΆ Analyzer (Claude) βββΆ Storage (SQLite) β+β β β β β+β βΌ βΌ βΌ β+β Reddit JSON Insights Reports & Alerts β+β β β+β βββββββ΄ββββββ β+β β β β+β Dashboard Integrations β+β (Web UI) (Slack/Email/ β+β Notion) β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## Project Structure++```+reddit-research/+βββ src/+β βββ reddit/ # Reddit API fetching+β βββ agent/ # Analysis, runner, multi-agent+β βββ db/ # SQLite storage+β βββ alerts/ # Slack & Email notifications+β βββ sync/ # Notion integration+β βββ dashboard/ # Web UI server+β βββ utils/ # Rate limiting, helpers+βββ docs/ # Documentation+β βββ ARCHITECTURE.md+β βββ QUICKSTART.md+β βββ API.md+βββ *.py # Python quick scripts+βββ package.json+```++## Documentation++- [Quick Start Guide](docs/QUICKSTART.md)+- [Architecture Overview](docs/ARCHITECTURE.md)+- [API Reference](docs/API.md)++## Production Features++### Web Dashboard+Browse insights visually at `http://localhost:3456`:+- Pain points, opportunities, competitors, buying signals+- Top subreddits and recent scan stats+- JSON API at `/api` for custom integrations++### Alerts (Slack & Email)+Get notified on high-value thread discoveries:+```bash+export SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...+export EMAIL_API_KEY=re_xxx # Resend or SendGrid+export EMAIL_PROVIDER=resend+export [email protected]+export [email protected]+```++### Notion Sync+Auto-push insights to your Notion workspace:+```bash+export NOTION_API_KEY=secret_xxx+export NOTION_PARENT_PAGE_ID=xxx-xxx-xxx # or NOTION_DATABASE_ID+```++### Rate Limiting+Built-in token bucket rate limiter with exponential backoff prevents Reddit blocking (60 req/min limit handled automatically).++### Multi-Agent Parallel Scanning+Scan multiple subreddits concurrently:+```bash+npx tsx src/agent/index.ts parallel "SaaS,entrepreneur,webdev" --queries "wish existed,frustrated"+```++## Cost++| Operation | Cost |+|-----------|------|+| Reddit fetching | Free |+| Quick analysis | Free |+| Claude analysis | ~$0.01/thread |+| 100 threads/day | ~$1/day |++## License++MIT++---++π° *"There is a lot of MONEY in niche subreddits"*diff --git a/agents/reddit-research/analyze_thread.py b/agents/reddit-research/analyze_thread.pynew file mode 100644index 0000000..fb029c9--- /dev/null+++ b/agents/reddit-research/analyze_thread.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+"""+Reddit Thread Analyzer+Fetches Reddit thread and analyzes with Claude for market research insights.++Usage:+ python analyze_thread.py <reddit_url>+ python analyze_thread.py https://www.reddit.com/r/SaaS/comments/xyz/title/++Outputs structured market research analysis.+"""++import json+import subprocess+import sys+from datetime import datetime++# Import from our extractor+from reddit_extractor import structure_for_analysis, format_for_llm, ANALYSIS_PROMPT+++def analyze_with_claude(thread_markdown: str) -> str:+ """Send thread to Claude for analysis via claude CLI."""+ full_prompt = ANALYSIS_PROMPT + "\n\n" + thread_markdown++ # Use claude CLI in non-interactive mode+ result = subprocess.run(+ ['claude', '-p', full_prompt, '--no-input'],+ capture_output=True,+ text=True,+ timeout=120+ )++ if result.returncode != 0:+ raise Exception(f"Claude analysis failed: {result.stderr}")++ return result.stdout+++def main():+ if len(sys.argv) < 2:+ print("Usage: python analyze_thread.py <reddit_url>")+ sys.exit(1)++ url = sys.argv[1]+ save_json = '--json' in sys.argv++ print(f"π Fetching thread: {url}")+ print("-" * 60)++ try:+ # Extract thread data+ data = structure_for_analysis(url)+ thread_md = format_for_llm(data)++ print(f"β Extracted {data['metrics']['total_comments']} comments from {data['metrics']['unique_authors']} authors")+ print(f"π Post score: {data['post']['score']} | Upvote ratio: {data['post']['upvote_ratio']}")+ print("-" * 60)++ # Save raw data if requested+ if save_json:+ json_file = f"thread_{data['post']['id'] if 'id' in data['post'] else 'export'}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"+ with open(json_file, 'w') as f:+ json.dump(data, f, indent=2, default=str)+ print(f"πΎ Saved raw data to: {json_file}")++ print("\nπ€ Analyzing with Claude...")+ print("=" * 60)++ analysis = analyze_with_claude(thread_md)+ print(analysis)++ # Save analysis+ analysis_file = f"analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"+ with open(analysis_file, 'w') as f:+ f.write(f"# Market Research Analysis\n\n")+ f.write(f"**Source:** {url}\n")+ f.write(f"**Analyzed:** {datetime.now().isoformat()}\n\n")+ f.write(analysis)++ print(f"\nπΎ Analysis saved to: {analysis_file}")++ except Exception as e:+ print(f"β Error: {e}", file=sys.stderr)+ sys.exit(1)+++if __name__ == '__main__':+ main()diff --git a/agents/reddit-research/docs/API.md b/agents/reddit-research/docs/API.mdnew file mode 100644index 0000000..926e32a--- /dev/null+++ b/agents/reddit-research/docs/API.md@@ -0,0 +1,274 @@+# Reddit Research Agent - API Reference++## TypeScript API++### Reddit Fetcher++#### `fetchThread(url: string): Promise<ThreadData>`++Fetch and parse a complete Reddit thread with all comments.++```typescript+import { fetchThread } from './reddit';++const thread = await fetchThread('https://reddit.com/r/SaaS/comments/xyz/title/');++console.log(thread.post.title);+console.log(thread.metrics.totalComments);+console.log(thread.topComments[0].body);+```++#### `searchSubreddit(subreddit, query?, options?): Promise<GoldmineScore[]>`++Search a subreddit for matching threads.++```typescript+import { searchSubreddit } from './reddit';++const threads = await searchSubreddit('SaaS', 'wish existed', {+ sort: 'top',+ time: 'year',+ limit: 25+});+```++#### `findGoldmineThreads(subreddit, queries?): Promise<GoldmineScore[]>`++Run multiple goldmine searches and return deduplicated, scored results.++```typescript+import { findGoldmineThreads } from './reddit';++// Uses default goldmine queries+const threads = await findGoldmineThreads('entrepreneur');++// Or specify custom queries+const customThreads = await findGoldmineThreads('smallbusiness', [+ 'software recommendation',+ 'tool for',+ 'automate'+]);+```++### Analyzer++#### `analyzeThread(data: ThreadData, options?): Promise<MarketInsight>`++Analyze a thread using Claude and extract structured insights.++```typescript+import { fetchThread } from './reddit';+import { analyzeThread } from './agent/analyzer';++const thread = await fetchThread(url);+const insights = await analyzeThread(thread, {+ apiKey: process.env.ANTHROPIC_API_KEY+});++console.log(insights.painPoints);+console.log(insights.opportunities);+console.log(insights.summary);+```++#### `quickAnalyze(data: ThreadData): Partial<MarketInsight>`++Fast pattern-based analysis without Claude (free).++```typescript+import { quickAnalyze } from './agent/analyzer';++const quick = quickAnalyze(thread);+console.log(quick.competitorMentions);+console.log(quick.buyingSignals);+```++### Database++#### `initDatabase(dbPath?: string): Database`++Initialize SQLite database connection.++```typescript+import { initDatabase } from './db';++const db = initDatabase('./my-research.db');+```++#### `saveThreads(threads: GoldmineScore[]): number`++Save scanned threads to database. Returns count saved.++```typescript+import { saveThreads } from './db';++const count = saveThreads(goldmineThreads);+```++#### `saveInsight(threadId, type, content, metadata?, confidence?): string`++Save a market insight. Returns insight ID.++```typescript+import { saveInsight } from './db';++const id = saveInsight(+ 'thread123',+ 'pain_point',+ 'Manual order processing is time-consuming',+ { frequency: 5, sentiment: 'frustrated' },+ 'high'+);+```++#### `getInsightsByType(type, limit?): Insight[]`++Query insights by type.++```typescript+import { getInsightsByType } from './db';++const painPoints = getInsightsByType('pain_point', 50);+const opportunities = getInsightsByType('opportunity');+const competitors = getInsightsByType('competitor');+```++### Agent Runner++#### `runScanCycle(options?): Promise<ScanResult>`++Run a single scan and analysis cycle.++```typescript+import { runScanCycle } from './agent/runner';++const result = await runScanCycle({+ dbPath: './research.db',+ maxThreadsPerScan: 20,+ minGoldmineScore: 15,+ useClaudeAnalysis: true,+ verbose: true+});++console.log(`Scanned: ${result.threadsScanned}`);+console.log(`Insights: ${result.insightsFound}`);+console.log(`Cost: $${result.costUsd}`);+```++#### `startScheduledAgent(schedule?, options?): void`++Start a continuously running scheduled agent.++```typescript+import { startScheduledAgent } from './agent/runner';++// Daily at 9 AM+startScheduledAgent('0 9 * * *', { verbose: true });++// Every 6 hours+startScheduledAgent('0 */6 * * *');+```++## Types++### ThreadData++```typescript+interface ThreadData {+ extractedAt: string;+ post: RedditPost;+ metrics: ThreadMetrics;+ topComments: RedditComment[];+ allComments: RedditComment[];+}+```++### RedditPost++```typescript+interface RedditPost {+ id: string;+ title: string;+ selftext: string;+ score: number;+ upvoteRatio: number;+ numComments: number;+ author: string;+ subreddit: string;+ permalink: string;+ url: string;+ createdUtc: number;+ flair?: string;+}+```++### MarketInsight++```typescript+interface MarketInsight {+ id: string;+ threadUrl: string;+ subreddit: string;+ extractedAt: string;+ painPoints: PainPoint[];+ opportunities: Opportunity[];+ competitorMentions: CompetitorMention[];+ buyingSignals: BuyingSignal[];+ keyQuotes: KeyQuote[];+ summary: string;+}+```++### GoldmineScore++```typescript+interface GoldmineScore {+ url: string;+ title: string;+ score: number;+ numComments: number;+ upvoteRatio: number;+ goldmineScore: number;+ subreddit: string;+}+```++## Python Scripts++### find_goldmine_threads.py++```bash+python3 find_goldmine_threads.py <subreddit> [--query "search terms"]++# Examples+python3 find_goldmine_threads.py SaaS+python3 find_goldmine_threads.py entrepreneur --query "frustrating"+```++### reddit_extractor.py++```bash+python3 reddit_extractor.py <url> [--json] [--prompt]++# Examples+python3 reddit_extractor.py "https://reddit.com/r/..."+python3 reddit_extractor.py "https://reddit.com/r/..." --json > data.json+python3 reddit_extractor.py "https://reddit.com/r/..." --prompt > for_claude.txt+```++## Error Handling++All async functions may throw errors. Wrap in try/catch:++```typescript+try {+ const thread = await fetchThread(url);+} catch (error) {+ if (error.message.includes('403')) {+ console.error('Reddit blocked request - try again later');+ } else if (error.message.includes('Empty response')) {+ console.error('Thread may be deleted or private');+ } else {+ throw error;+ }+}+```diff --git a/agents/reddit-research/docs/ARCHITECTURE.md b/agents/reddit-research/docs/ARCHITECTURE.mdnew file mode 100644index 0000000..728d36c--- /dev/null+++ b/agents/reddit-research/docs/ARCHITECTURE.md@@ -0,0 +1,174 @@+# Reddit Research Agent - Architecture++## Overview++The Reddit Research Agent is an autonomous system that discovers market research opportunities from Reddit discussions. It uses the hidden `.json` API endpoint to extract complete thread data, analyzes content with Claude, and stores structured insights in SQLite.++## System Architecture++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β Reddit Research Agent β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β+β β Scanner βββββΆβ Analyzer βββββΆβ Storage β β+β β β β (Claude) β β (SQLite) β β+β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β+β β β β β+β βΌ βΌ βΌ β+β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β+β β Reddit JSON β β Insights β β Reports β β+β β API β β Extraction β β & Alerts β β+β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β+β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## Core Components++### 1. Reddit Fetcher (`src/reddit/fetcher.ts`)++Handles all Reddit API interactions using the hidden JSON endpoint.++**Key Functions:**+- `fetchThread(url)` - Extracts complete thread with nested comments+- `searchSubreddit(subreddit, query)` - Searches for relevant threads+- `findGoldmineThreads(subreddit)` - Runs multiple searches to find high-value content++**The Trick:**+```+https://reddit.com/r/SaaS/comments/xyz/title/+ β Add .json+https://reddit.com/r/SaaS/comments/xyz/title/.json+```++### 2. Thread Analyzer (`src/agent/analyzer.ts`)++Analyzes thread content to extract market insights.++**Two Modes:**+1. **Claude Analysis** - Full LLM analysis for deep insights+2. **Quick Analysis** - Pattern matching for fast, free scanning++**Extracted Insights:**+- Pain Points (with frequency and sentiment)+- Product Opportunities (with confidence levels)+- Competitor Mentions (positive/negative/neutral)+- Buying Signals (looking, considering, ready, switched)+- Key Quotes (high-engagement insights)++### 3. Database Layer (`src/db/`)++SQLite database for persistent storage.++**Tables:**+- `threads` - Scanned thread metadata+- `insights` - Extracted market insights+- `agent_runs` - Run history and stats+- `tracked_sources` - Configured subreddits/queries++### 4. Agent Runner (`src/agent/runner.ts`)++Orchestrates the full pipeline.++**Modes:**+- **Single Run** - One scan cycle+- **Scheduled** - Cron-based continuous monitoring++## Data Flow++```+1. SCAN+ βββΆ Search subreddits for goldmine queries+ βββΆ Calculate goldmine scores+ βββΆ Save threads to database++2. ANALYZE+ βββΆ Fetch full thread content+ βββΆ Send to Claude for analysis+ βββΆ Parse structured insights++3. STORE+ βββΆ Save insights by type+ βββΆ Mark thread as analyzed+ βββΆ Update run statistics++4. REPORT (future)+ βββΆ Generate summaries+ βββΆ Send alerts+ βββΆ Export to Notion+```++## Goldmine Score Algorithm++Threads are scored to prioritize high-value content:++```typescript+score = 0++// Engagement signals+score += min(numComments / 10, 20) // Up to 20 pts+score += upvoteRatio * 10 // Up to 10 pts+score += min(postScore / 50, 10) // Up to 10 pts++// Content signals (keywords in title)+goldmineKeywords = ['wish', 'hate', 'frustrating', 'recommend', ...]+for (keyword in goldmineKeywords) {+ if (title.includes(keyword)) score += 3+}+```++## Configuration++### Environment Variables++```bash+ANTHROPIC_API_KEY=sk-ant-... # Required for Claude analysis+```++### Tracked Sources++```typescript+// Add via CLI+npx tsx src/agent/index.ts add SaaS "wish existed"+npx tsx src/agent/index.ts add entrepreneur++// Or programmatically+addTrackedSource('smallbusiness', 'software');+```++### Schedule++```typescript+// Default: Daily at 9 AM+startScheduledAgent('0 9 * * *');++// Every 6 hours+startScheduledAgent('0 */6 * * *');++// Every hour+startScheduledAgent('0 * * * *');+```++## Cost Estimation++| Operation | Est. Cost |+|-----------|-----------|+| Reddit fetch | Free |+| Quick analysis | Free |+| Claude analysis | ~$0.01/thread |+| 100 threads/day | ~$1/day |++## Scaling Considerations++### Current Limits+- Reddit rate limits (need delays between requests)+- SQLite single-writer (fine for single agent)+- Claude API costs scale linearly++### Future Optimizations+- Batch Reddit requests+- PostgreSQL for multi-agent+- Caching for frequently-accessed threads+- Priority queue for analysisdiff --git a/agents/reddit-research/docs/QUICKSTART.md b/agents/reddit-research/docs/QUICKSTART.mdnew file mode 100644index 0000000..a2577cc--- /dev/null+++ b/agents/reddit-research/docs/QUICKSTART.md@@ -0,0 +1,165 @@+# Reddit Research Agent - Quick Start++## Installation++```bash+cd reddit-research+npm install+```++## Required Setup++Set your Anthropic API key (for Claude analysis):++```bash+export ANTHROPIC_API_KEY=sk-ant-...+```++## Usage++### 1. Find Goldmine Threads (Python - Quick)++```bash+# Scan a subreddit+python3 find_goldmine_threads.py SaaS++# Search with specific query+python3 find_goldmine_threads.py entrepreneur --query "frustrating"++# Output: List of high-value threads sorted by goldmine score+```++### 2. Extract Thread Data (Python)++```bash+# Get formatted markdown+python3 reddit_extractor.py "https://reddit.com/r/SaaS/comments/xyz/title/"++# Get JSON for programmatic use+python3 reddit_extractor.py "https://reddit.com/r/SaaS/comments/..." --json++# Include analysis prompt+python3 reddit_extractor.py "https://reddit.com/r/SaaS/comments/..." --prompt+```++### 3. Run the TypeScript Agent++```bash+# Single scan cycle+npx tsx src/agent/index.ts run++# Start scheduled agent (daily at 9 AM)+npx tsx src/agent/index.ts schedule++# Custom schedule (every 6 hours)+npx tsx src/agent/index.ts schedule "0 */6 * * *"+```++### 4. Manage Tracked Sources++```bash+# Add subreddit+npx tsx src/agent/index.ts add SaaS++# Add subreddit with specific query+npx tsx src/agent/index.ts add entrepreneur "wish existed"++# List configured sources+npx tsx src/agent/index.ts sources+```++### 5. View Statistics++```bash+npx tsx src/agent/index.ts stats+```++## Example Workflow++```bash+# 1. Find interesting threads+python3 find_goldmine_threads.py smallbusiness --query "software"++# 2. Extract and analyze top thread+python3 reddit_extractor.py "https://reddit.com/r/smallbusiness/comments/..." --prompt > analysis.txt++# 3. Run full agent for automated insights+npx tsx src/agent/index.ts add smallbusiness "software"+npx tsx src/agent/index.ts run++# 4. Check results+npx tsx src/agent/index.ts stats+```++## High-Value Subreddits++### B2B / SaaS+- r/SaaS+- r/startups+- r/entrepreneur+- r/smallbusiness++### Developer Tools+- r/webdev+- r/programming+- r/devops+- r/sysadmin++### Consumer+- r/productivity+- r/ADHD+- r/homelab+- Any niche hobby subreddit++## Goldmine Queries++The agent automatically searches for these high-value phrases:++- "wish existed"+- "hate about"+- "frustrating"+- "looking for"+- "recommend"+- "alternative to"+- "switched from"+- "paying for"+- "game changer"++## Output Format++### Thread Analysis++```+# Reddit Thread Analysis++**Subreddit:** r/SaaS+**Title:** What's One Thing You Wish You Did Differently?+**Score:** 351 | **Upvote Ratio:** 99%+**Comments:** 80 | **Unique Authors:** 45++## Pain Points+- No validation before building (3 mentions)+- Can't sell as introvert (high engagement)+- Distribution/visibility challenges++## Opportunities+- [high] Validation-as-a-Service tool+- [medium] Sales training for technical founders+- [low] Growth loop templates++## Competitor Mentions+- Canva (neutral) - mentioned 5 times+- Notion (positive) - mentioned 3 times++## Key Quotes+> "I hired sales, for one year I didn't get any client. Now I do sales myself..."+```++## Database Location++By default, data is stored in `./reddit-research.db` (SQLite).++View raw data:+```bash+sqlite3 reddit-research.db "SELECT * FROM insights ORDER BY created_at DESC LIMIT 10;"+```diff --git a/agents/reddit-research/find_goldmine_threads.py b/agents/reddit-research/find_goldmine_threads.pynew file mode 100644index 0000000..b9a97b4--- /dev/null+++ b/agents/reddit-research/find_goldmine_threads.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""+Reddit Goldmine Thread Finder+Searches subreddits for high-value market research threads.++Usage:+ python find_goldmine_threads.py <subreddit> [--query "search terms"]+ python find_goldmine_threads.py SaaS --query "wish existed"+ python find_goldmine_threads.py smallbusiness++Finds threads with high engagement that reveal:+- Pain points and frustrations+- Product requests and gaps+- Buying signals+- Competitor discussions+"""++import json+import subprocess+import sys+import urllib.parse+from datetime import datetime++USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"++# High-value search queries for market research+GOLDMINE_QUERIES = [+ "wish existed",+ "hate about",+ "frustrating",+ "looking for",+ "recommend",+ "alternative to",+ "switched from",+ "anyone using",+ "what software",+ "how do you",+ "best tool for",+ "paying for",+ "waste of money",+ "game changer",+ "changed my life",+]+++def fetch_json(url: str) -> dict:+ """Fetch URL as JSON using curl."""+ result = subprocess.run(+ ['curl', '-s', '-A', USER_AGENT, url],+ capture_output=True,+ text=True,+ timeout=30+ )+ if result.returncode != 0 or not result.stdout:+ raise Exception(f"curl failed: {result.stderr or 'empty response'}")+ try:+ return json.loads(result.stdout)+ except json.JSONDecodeError as e:+ raise Exception(f"Invalid JSON response: {e}")+++def search_subreddit(subreddit: str, query: str = None, sort: str = "top", time: str = "year", limit: int = 25) -> list:+ """Search a subreddit for threads."""+ if query:+ encoded_query = urllib.parse.quote(query)+ url = f"https://www.reddit.com/r/{subreddit}/search.json?q={encoded_query}&restrict_sr=1&sort={sort}&t={time}&limit={limit}"+ else:+ url = f"https://www.reddit.com/r/{subreddit}/{sort}.json?t={time}&limit={limit}"++ data = fetch_json(url)+ threads = []++ for post in data.get('data', {}).get('children', []):+ p = post['data']+ threads.append({+ 'title': p.get('title', ''),+ 'score': p.get('score', 0),+ 'num_comments': p.get('num_comments', 0),+ 'upvote_ratio': p.get('upvote_ratio', 0),+ 'url': f"https://reddit.com{p.get('permalink', '')}",+ 'created_utc': p.get('created_utc'),+ 'author': p.get('author', '[deleted]'),+ 'selftext_preview': p.get('selftext', '')[:200],+ 'flair': p.get('link_flair_text'),+ })++ return threads+++def calculate_goldmine_score(thread: dict) -> float:+ """Calculate how valuable a thread is for market research."""+ score = 0++ # High comment count = lots of discussion+ score += min(thread['num_comments'] / 10, 20) # Up to 20 pts++ # Good upvote ratio = quality content+ score += thread['upvote_ratio'] * 10 # Up to 10 pts++ # Post score indicates visibility+ score += min(thread['score'] / 50, 10) # Up to 10 pts++ # Bonus for certain keywords in title+ title_lower = thread['title'].lower()+ goldmine_keywords = ['wish', 'hate', 'love', 'best', 'worst', 'looking for',+ 'recommend', 'help', 'advice', 'alternative', 'switched',+ 'paying', 'worth it', 'frustrat', 'problem', 'solution']+ for kw in goldmine_keywords:+ if kw in title_lower:+ score += 3++ return round(score, 2)+++def main():+ if len(sys.argv) < 2:+ print("Usage: python find_goldmine_threads.py <subreddit> [--query \"search terms\"]")+ print("\nExamples:")+ print(" python find_goldmine_threads.py SaaS")+ print(" python find_goldmine_threads.py smallbusiness --query \"software\"")+ print(" python find_goldmine_threads.py entrepreneur --query \"wish existed\"")+ sys.exit(1)++ subreddit = sys.argv[1]+ query = None++ # Parse --query argument+ if '--query' in sys.argv:+ idx = sys.argv.index('--query')+ if idx + 1 < len(sys.argv):+ query = sys.argv[idx + 1]++ print(f"π Scanning r/{subreddit}" + (f" for '{query}'" if query else ""))+ print("=" * 70)++ all_threads = []++ if query:+ # Single search+ threads = search_subreddit(subreddit, query)+ all_threads.extend(threads)+ else:+ # Multiple goldmine searches+ print(f"Running {len(GOLDMINE_QUERIES)} goldmine queries...")+ for gq in GOLDMINE_QUERIES:+ try:+ threads = search_subreddit(subreddit, gq, limit=10)+ all_threads.extend(threads)+ print(f" β '{gq}': {len(threads)} threads")+ except Exception as e:+ print(f" β '{gq}': {e}")++ # Deduplicate by URL+ seen_urls = set()+ unique_threads = []+ for t in all_threads:+ if t['url'] not in seen_urls:+ seen_urls.add(t['url'])+ t['goldmine_score'] = calculate_goldmine_score(t)+ unique_threads.append(t)++ # Sort by goldmine score+ unique_threads.sort(key=lambda x: x['goldmine_score'], reverse=True)++ print(f"\nπ TOP {min(20, len(unique_threads))} GOLDMINE THREADS")+ print("=" * 70)++ for i, t in enumerate(unique_threads[:20], 1):+ print(f"\n{i}. [Score: {t['goldmine_score']}] {t['title'][:70]}")+ print(f" π {t['score']} pts | π¬ {t['num_comments']} comments | π {t['upvote_ratio']:.0%}")+ print(f" π {t['url']}")++ # Save results+ output_file = f"goldmine_{subreddit}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"+ with open(output_file, 'w') as f:+ json.dump({+ 'subreddit': subreddit,+ 'query': query,+ 'scanned_at': datetime.now().isoformat(),+ 'threads': unique_threads+ }, f, indent=2)++ print(f"\nπΎ Saved {len(unique_threads)} threads to: {output_file}")+ print("\nNext: Run `python analyze_thread.py <url>` on any thread above")+++if __name__ == '__main__':+ main()diff --git a/agents/reddit-research/package-lock.json b/agents/reddit-research/package-lock.jsonnew file mode 100644index 0000000..a2fdf0b--- /dev/null+++ b/agents/reddit-research/package-lock.json@@ -0,0 +1,2852 @@+{+ "name": "reddit-research-agent",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "reddit-research-agent",+ "version": "1.0.0",+ "license": "MIT",+ "dependencies": {+ "@anthropic-ai/sdk": "^0.39.0",+ "better-sqlite3": "^11.7.0",+ "node-cron": "^3.0.3",+ "zod": "^3.24.1"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.12",+ "@types/node": "^22.10.2",+ "@types/node-cron": "^3.0.11",+ "tsx": "^4.19.2",+ "typescript": "^5.7.2",+ "vitest": "^2.1.8"+ }+ },+ "node_modules/@anthropic-ai/sdk": {+ "version": "0.39.0",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.39.0.tgz",+ "integrity": "sha512-eMyDIPRZbt1CCLErRCi3exlAvNkBtRe+kW5vvJyef93PmNr/clstYgHhtvmkxN82nlKgzyGPCyGxrm0JQ1ZIdg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "^18.11.18",+ "@types/node-fetch": "^2.6.4",+ "abort-controller": "^3.0.0",+ "agentkeepalive": "^4.2.1",+ "form-data-encoder": "1.7.2",+ "formdata-node": "^4.3.2",+ "node-fetch": "^2.6.7"+ }+ },+ "node_modules/@anthropic-ai/sdk/node_modules/@types/node": {+ "version": "18.19.130",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",+ "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~5.26.4"+ }+ },+ "node_modules/@anthropic-ai/sdk/node_modules/undici-types": {+ "version": "5.26.5",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",+ "license": "MIT"+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.54.0.tgz",+ "integrity": "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.54.0.tgz",+ "integrity": "sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.54.0.tgz",+ "integrity": "sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.54.0.tgz",+ "integrity": "sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.54.0.tgz",+ "integrity": "sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.54.0.tgz",+ "integrity": "sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.54.0.tgz",+ "integrity": "sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.54.0.tgz",+ "integrity": "sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.54.0.tgz",+ "integrity": "sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.54.0.tgz",+ "integrity": "sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.54.0.tgz",+ "integrity": "sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.54.0.tgz",+ "integrity": "sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.54.0.tgz",+ "integrity": "sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.54.0.tgz",+ "integrity": "sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.54.0.tgz",+ "integrity": "sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.54.0.tgz",+ "integrity": "sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.54.0.tgz",+ "integrity": "sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.54.0.tgz",+ "integrity": "sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.54.0.tgz",+ "integrity": "sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.54.0.tgz",+ "integrity": "sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.54.0.tgz",+ "integrity": "sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.54.0.tgz",+ "integrity": "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@types/better-sqlite3": {+ "version": "7.6.13",+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "22.19.3",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.3.tgz",+ "integrity": "sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/node-cron": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",+ "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node-fetch": {+ "version": "2.6.13",+ "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz",+ "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "form-data": "^4.0.4"+ }+ },+ "node_modules/@vitest/expect": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",+ "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "2.1.9",+ "@vitest/utils": "2.1.9",+ "chai": "^5.1.2",+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",+ "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "2.1.9",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.12"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^5.0.0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",+ "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",+ "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "2.1.9",+ "pathe": "^1.1.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",+ "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "2.1.9",+ "magic-string": "^0.30.12",+ "pathe": "^1.1.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",+ "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyspy": "^3.0.2"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",+ "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "2.1.9",+ "loupe": "^3.1.2",+ "tinyrainbow": "^1.2.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/abort-controller": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",+ "license": "MIT",+ "dependencies": {+ "event-target-shim": "^5.0.0"+ },+ "engines": {+ "node": ">=6.5"+ }+ },+ "node_modules/agentkeepalive": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",+ "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==",+ "license": "MIT",+ "dependencies": {+ "humanize-ms": "^1.2.1"+ },+ "engines": {+ "node": ">= 8.0.0"+ }+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "license": "MIT"+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/better-sqlite3": {+ "version": "11.10.0",+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",+ "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ }+ },+ "node_modules/bindings": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",+ "license": "MIT",+ "dependencies": {+ "file-uri-to-path": "1.0.0"+ }+ },+ "node_modules/bl": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^5.5.0",+ "inherits": "^2.0.4",+ "readable-stream": "^3.4.0"+ }+ },+ "node_modules/buffer": {+ "version": "5.7.1",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.1.13"+ }+ },+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/chai": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "assertion-error": "^2.0.1",+ "check-error": "^2.1.1",+ "deep-eql": "^5.0.1",+ "loupe": "^3.1.0",+ "pathval": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/check-error": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz",+ "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ }+ },+ "node_modules/chownr": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",+ "license": "ISC"+ },+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "license": "MIT",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/deep-eql": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/deep-extend": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",+ "license": "MIT",+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.2",+ "@esbuild/android-arm": "0.27.2",+ "@esbuild/android-arm64": "0.27.2",+ "@esbuild/android-x64": "0.27.2",+ "@esbuild/darwin-arm64": "0.27.2",+ "@esbuild/darwin-x64": "0.27.2",+ "@esbuild/freebsd-arm64": "0.27.2",+ "@esbuild/freebsd-x64": "0.27.2",+ "@esbuild/linux-arm": "0.27.2",+ "@esbuild/linux-arm64": "0.27.2",+ "@esbuild/linux-ia32": "0.27.2",+ "@esbuild/linux-loong64": "0.27.2",+ "@esbuild/linux-mips64el": "0.27.2",+ "@esbuild/linux-ppc64": "0.27.2",+ "@esbuild/linux-riscv64": "0.27.2",+ "@esbuild/linux-s390x": "0.27.2",+ "@esbuild/linux-x64": "0.27.2",+ "@esbuild/netbsd-arm64": "0.27.2",+ "@esbuild/netbsd-x64": "0.27.2",+ "@esbuild/openbsd-arm64": "0.27.2",+ "@esbuild/openbsd-x64": "0.27.2",+ "@esbuild/openharmony-arm64": "0.27.2",+ "@esbuild/sunos-x64": "0.27.2",+ "@esbuild/win32-arm64": "0.27.2",+ "@esbuild/win32-ia32": "0.27.2",+ "@esbuild/win32-x64": "0.27.2"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/event-target-shim": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/expand-template": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",+ "license": "(MIT OR WTFPL)",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/expect-type": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/file-uri-to-path": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",+ "license": "MIT"+ },+ "node_modules/form-data": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.2",+ "mime-types": "^2.1.12"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/form-data-encoder": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",+ "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==",+ "license": "MIT"+ },+ "node_modules/formdata-node": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",+ "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",+ "license": "MIT",+ "dependencies": {+ "node-domexception": "1.0.0",+ "web-streams-polyfill": "4.0.0-beta.3"+ },+ "engines": {+ "node": ">= 12.20"+ }+ },+ "node_modules/fs-constants": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",+ "license": "MIT"+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.0",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz",+ "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/github-from-package": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",+ "license": "MIT"+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/humanize-ms": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",+ "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.0.0"+ }+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ini": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",+ "license": "ISC"+ },+ "node_modules/loupe": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mkdirp-classic": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",+ "license": "MIT"+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.11",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/napi-build-utils": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",+ "license": "MIT"+ },+ "node_modules/node-abi": {+ "version": "3.85.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.85.0.tgz",+ "integrity": "sha512-zsFhmbkAzwhTft6nd3VxcG0cvJsT70rL+BIGHWVq5fi6MwGrHwzqKaxXE+Hl2GmnGItnDKPPkO5/LQqjVkIdFg==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/node-cron": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",+ "integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",+ "license": "ISC",+ "dependencies": {+ "uuid": "8.3.2"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/node-domexception": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",+ "deprecated": "Use your platform's native DOMException instead",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "github",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=10.5.0"+ }+ },+ "node_modules/node-fetch": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "license": "MIT",+ "dependencies": {+ "whatwg-url": "^5.0.0"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ },+ "peerDependencies": {+ "encoding": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "encoding": {+ "optional": true+ }+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/pathe": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathval": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14.16"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/postcss": {+ "version": "8.5.6",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.11",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/prebuild-install": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",+ "license": "MIT",+ "dependencies": {+ "detect-libc": "^2.0.0",+ "expand-template": "^2.0.3",+ "github-from-package": "0.0.0",+ "minimist": "^1.2.3",+ "mkdirp-classic": "^0.5.3",+ "napi-build-utils": "^2.0.0",+ "node-abi": "^3.3.0",+ "pump": "^3.0.0",+ "rc": "^1.2.7",+ "simple-get": "^4.0.0",+ "tar-fs": "^2.0.0",+ "tunnel-agent": "^0.6.0"+ },+ "bin": {+ "prebuild-install": "bin.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/pump": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",+ "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/rc": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",+ "dependencies": {+ "deep-extend": "^0.6.0",+ "ini": "~1.3.0",+ "minimist": "^1.2.0",+ "strip-json-comments": "~2.0.1"+ },+ "bin": {+ "rc": "cli.js"+ }+ },+ "node_modules/readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "license": "MIT",+ "dependencies": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/rollup": {+ "version": "4.54.0",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.54.0.tgz",+ "integrity": "sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.8"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.54.0",+ "@rollup/rollup-android-arm64": "4.54.0",+ "@rollup/rollup-darwin-arm64": "4.54.0",+ "@rollup/rollup-darwin-x64": "4.54.0",+ "@rollup/rollup-freebsd-arm64": "4.54.0",+ "@rollup/rollup-freebsd-x64": "4.54.0",+ "@rollup/rollup-linux-arm-gnueabihf": "4.54.0",+ "@rollup/rollup-linux-arm-musleabihf": "4.54.0",+ "@rollup/rollup-linux-arm64-gnu": "4.54.0",+ "@rollup/rollup-linux-arm64-musl": "4.54.0",+ "@rollup/rollup-linux-loong64-gnu": "4.54.0",+ "@rollup/rollup-linux-ppc64-gnu": "4.54.0",+ "@rollup/rollup-linux-riscv64-gnu": "4.54.0",+ "@rollup/rollup-linux-riscv64-musl": "4.54.0",+ "@rollup/rollup-linux-s390x-gnu": "4.54.0",+ "@rollup/rollup-linux-x64-gnu": "4.54.0",+ "@rollup/rollup-linux-x64-musl": "4.54.0",+ "@rollup/rollup-openharmony-arm64": "4.54.0",+ "@rollup/rollup-win32-arm64-msvc": "4.54.0",+ "@rollup/rollup-win32-ia32-msvc": "4.54.0",+ "@rollup/rollup-win32-x64-gnu": "4.54.0",+ "@rollup/rollup-win32-x64-msvc": "4.54.0",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/simple-concat": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/simple-get": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decompress-response": "^6.0.0",+ "once": "^1.3.1",+ "simple-concat": "^1.0.0"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/std-env": {+ "version": "3.10.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.2.0"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/tar-fs": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",+ "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",+ "license": "MIT",+ "dependencies": {+ "chownr": "^1.1.1",+ "mkdirp-classic": "^0.5.2",+ "pump": "^3.0.0",+ "tar-stream": "^2.1.4"+ }+ },+ "node_modules/tar-stream": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",+ "license": "MIT",+ "dependencies": {+ "bl": "^4.0.3",+ "end-of-stream": "^1.4.1",+ "fs-constants": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^3.1.1"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinypool": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",+ "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tinyspy": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",+ "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tr46": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "license": "MIT"+ },+ "node_modules/tsx": {+ "version": "4.21.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.27.0",+ "get-tsconfig": "^4.7.5"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/tunnel-agent": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "license": "MIT"+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/uuid": {+ "version": "8.3.2",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",+ "license": "MIT",+ "bin": {+ "uuid": "dist/bin/uuid"+ }+ },+ "node_modules/vite": {+ "version": "5.4.21",+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.21.3",+ "postcss": "^8.4.43",+ "rollup": "^4.20.0"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^18.0.0 || >=20.0.0",+ "less": "*",+ "lightningcss": "^1.21.0",+ "sass": "*",+ "sass-embedded": "*",+ "stylus": "*",+ "sugarss": "*",+ "terser": "^5.4.0"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ }+ }+ },+ "node_modules/vite-node": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",+ "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cac": "^6.7.14",+ "debug": "^4.3.7",+ "es-module-lexer": "^1.5.4",+ "pathe": "^1.1.2",+ "vite": "^5.0.0"+ },+ "bin": {+ "vite-node": "vite-node.mjs"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/vite/node_modules/@esbuild/aix-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/android-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/android-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/android-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/darwin-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/darwin-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/freebsd-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/freebsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-loong64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-mips64el": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-riscv64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-s390x": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/linux-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/netbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/openbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/sunos-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/win32-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/win32-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/@esbuild/win32-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/vite/node_modules/esbuild": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.21.5",+ "@esbuild/android-arm": "0.21.5",+ "@esbuild/android-arm64": "0.21.5",+ "@esbuild/android-x64": "0.21.5",+ "@esbuild/darwin-arm64": "0.21.5",+ "@esbuild/darwin-x64": "0.21.5",+ "@esbuild/freebsd-arm64": "0.21.5",+ "@esbuild/freebsd-x64": "0.21.5",+ "@esbuild/linux-arm": "0.21.5",+ "@esbuild/linux-arm64": "0.21.5",+ "@esbuild/linux-ia32": "0.21.5",+ "@esbuild/linux-loong64": "0.21.5",+ "@esbuild/linux-mips64el": "0.21.5",+ "@esbuild/linux-ppc64": "0.21.5",+ "@esbuild/linux-riscv64": "0.21.5",+ "@esbuild/linux-s390x": "0.21.5",+ "@esbuild/linux-x64": "0.21.5",+ "@esbuild/netbsd-x64": "0.21.5",+ "@esbuild/openbsd-x64": "0.21.5",+ "@esbuild/sunos-x64": "0.21.5",+ "@esbuild/win32-arm64": "0.21.5",+ "@esbuild/win32-ia32": "0.21.5",+ "@esbuild/win32-x64": "0.21.5"+ }+ },+ "node_modules/vitest": {+ "version": "2.1.9",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",+ "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "2.1.9",+ "@vitest/mocker": "2.1.9",+ "@vitest/pretty-format": "^2.1.9",+ "@vitest/runner": "2.1.9",+ "@vitest/snapshot": "2.1.9",+ "@vitest/spy": "2.1.9",+ "@vitest/utils": "2.1.9",+ "chai": "^5.1.2",+ "debug": "^4.3.7",+ "expect-type": "^1.1.0",+ "magic-string": "^0.30.12",+ "pathe": "^1.1.2",+ "std-env": "^3.8.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^0.3.1",+ "tinypool": "^1.0.1",+ "tinyrainbow": "^1.2.0",+ "vite": "^5.0.0",+ "vite-node": "2.1.9",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@types/node": "^18.0.0 || >=20.0.0",+ "@vitest/browser": "2.1.9",+ "@vitest/ui": "2.1.9",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },+ "node_modules/web-streams-polyfill": {+ "version": "4.0.0-beta.3",+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",+ "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",+ "license": "MIT",+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/whatwg-url": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "license": "MIT",+ "dependencies": {+ "tr46": "~0.0.3",+ "webidl-conversions": "^3.0.0"+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/agents/reddit-research/package.json b/agents/reddit-research/package.jsonnew file mode 100644index 0000000..6228947--- /dev/null+++ b/agents/reddit-research/package.json@@ -0,0 +1,44 @@+{+ "name": "reddit-research-agent",+ "version": "1.0.0",+ "description": "Autonomous Reddit research agent for market intelligence",+ "type": "module",+ "main": "dist/index.js",+ "scripts": {+ "build": "tsc",+ "dev": "tsx watch src/index.ts",+ "start": "node dist/index.js",+ "scan": "tsx src/cli/scan.ts",+ "analyze": "tsx src/cli/analyze.ts",+ "agent": "tsx src/agent/index.ts",+ "agent:run": "tsx src/agent/index.ts run",+ "agent:schedule": "tsx src/agent/index.ts schedule",+ "dashboard": "tsx src/agent/index.ts dashboard",+ "parallel": "tsx src/agent/index.ts parallel",+ "test": "vitest",+ "typecheck": "tsc --noEmit"+ },+ "keywords": [+ "reddit",+ "market-research",+ "ai-agent",+ "claude",+ "niche-research"+ ],+ "author": "ID8Labs",+ "license": "MIT",+ "dependencies": {+ "@anthropic-ai/sdk": "^0.39.0",+ "better-sqlite3": "^11.7.0",+ "node-cron": "^3.0.3",+ "zod": "^3.24.1"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.12",+ "@types/node": "^22.10.2",+ "@types/node-cron": "^3.0.11",+ "tsx": "^4.19.2",+ "typescript": "^5.7.2",+ "vitest": "^2.1.8"+ }+}diff --git a/agents/reddit-research/reddit_extractor.py b/agents/reddit-research/reddit_extractor.pynew file mode 100644index 0000000..f153e20--- /dev/null+++ b/agents/reddit-research/reddit_extractor.py@@ -0,0 +1,213 @@+#!/usr/bin/env python3+"""+Reddit Research Extractor+Extracts threads via JSON API and structures data for LLM analysis.++Usage:+ python reddit_extractor.py <reddit_url>+ python reddit_extractor.py https://www.reddit.com/r/SaaS/comments/xyz/title/+"""++import json+import subprocess+import sys+from datetime import datetime+from typing import Optional++USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"+++def fetch_reddit_json(url: str) -> dict:+ """Fetch Reddit thread as JSON using curl (bypasses urllib fingerprinting)."""+ # Normalize URL to use www.reddit.com+ url = url.replace('reddit.com', 'www.reddit.com')+ if 'www.www.' in url:+ url = url.replace('www.www.', 'www.')++ # Normalize URL to JSON endpoint+ if not url.endswith('.json'):+ url = url.rstrip('/') + '.json'++ result = subprocess.run(+ ['curl', '-s', '-A', USER_AGENT, url],+ capture_output=True,+ text=True,+ timeout=30+ )+ if result.returncode != 0:+ raise Exception(f"curl failed: {result.stderr}")+ return json.loads(result.stdout)+++def extract_comments(children: list, depth: int = 0) -> list:+ """Recursively extract all comments from thread."""+ results = []+ for c in children:+ if c['kind'] == 't1': # t1 = comment+ d = c['data']+ comment = {+ 'score': d.get('score', 0),+ 'author': d.get('author', '[deleted]'),+ 'body': d.get('body', ''),+ 'created_utc': d.get('created_utc'),+ 'depth': depth,+ 'id': d.get('id'),+ 'replies_count': 0+ }++ # Count and extract replies+ replies = []+ if d.get('replies') and isinstance(d['replies'], dict):+ reply_children = d['replies']['data']['children']+ replies = extract_comments(reply_children, depth + 1)+ comment['replies_count'] = len(replies)++ results.append(comment)+ results.extend(replies)++ return results+++def structure_for_analysis(url: str) -> dict:+ """Extract and structure Reddit thread for LLM analysis."""+ data = fetch_reddit_json(url)++ # Extract post+ post_data = data[0]['data']['children'][0]['data']+ post = {+ 'title': post_data.get('title', ''),+ 'selftext': post_data.get('selftext', ''),+ 'score': post_data.get('score', 0),+ 'upvote_ratio': post_data.get('upvote_ratio', 0),+ 'num_comments': post_data.get('num_comments', 0),+ 'author': post_data.get('author', '[deleted]'),+ 'created_utc': post_data.get('created_utc'),+ 'subreddit': post_data.get('subreddit', ''),+ 'url': f"https://reddit.com{post_data.get('permalink', '')}",+ 'flair': post_data.get('link_flair_text'),+ }++ # Extract all comments+ comments = extract_comments(data[1]['data']['children'])++ # Sort by score for top comments+ top_comments = sorted(comments, key=lambda x: x['score'], reverse=True)++ # Calculate engagement metrics+ total_comment_score = sum(c['score'] for c in comments)+ avg_comment_score = total_comment_score / len(comments) if comments else 0++ return {+ 'extracted_at': datetime.utcnow().isoformat(),+ 'post': post,+ 'metrics': {+ 'total_comments': len(comments),+ 'total_comment_score': total_comment_score,+ 'avg_comment_score': round(avg_comment_score, 2),+ 'max_depth': max((c['depth'] for c in comments), default=0),+ 'unique_authors': len(set(c['author'] for c in comments)),+ },+ 'top_comments': top_comments[:30], # Top 30 by score+ 'all_comments': comments, # Full thread+ }+++def format_for_llm(data: dict, include_all: bool = False) -> str:+ """Format extracted data as markdown for LLM analysis."""+ post = data['post']+ metrics = data['metrics']++ output = []+ output.append(f"# Reddit Thread Analysis\n")+ output.append(f"**Subreddit:** r/{post['subreddit']}")+ output.append(f"**Title:** {post['title']}")+ output.append(f"**Score:** {post['score']} | **Upvote Ratio:** {post['upvote_ratio']}")+ output.append(f"**Comments:** {post['num_comments']} | **Unique Authors:** {metrics['unique_authors']}")+ output.append(f"**URL:** {post['url']}\n")++ output.append("## Original Post\n")+ output.append(post['selftext'] or "*No text content*")+ output.append("\n")++ output.append("## Engagement Metrics\n")+ output.append(f"- Total comment score: {metrics['total_comment_score']}")+ output.append(f"- Avg comment score: {metrics['avg_comment_score']}")+ output.append(f"- Max thread depth: {metrics['max_depth']}")+ output.append("\n")++ comments = data['all_comments'] if include_all else data['top_comments']+ output.append(f"## {'All' if include_all else 'Top'} Comments ({len(comments)})\n")++ for i, c in enumerate(comments, 1):+ indent = " " * c['depth']+ output.append(f"{indent}### [{c['score']} pts] u/{c['author']}")+ body = c['body'].replace('\n', '\n' + indent)+ output.append(f"{indent}{body}")+ output.append("")++ return '\n'.join(output)+++# Analysis prompt template+ANALYSIS_PROMPT = """+Analyze this Reddit thread for market research insights. Extract:++## 1. Pain Points+- What problems are people experiencing?+- What frustrations are expressed?+- What's missing from current solutions?++## 2. Product/Competitor Mentions+- What products/services are mentioned (positively or negatively)?+- What alternatives do people suggest?++## 3. Buying Signals+- Who is actively looking for solutions?+- What would make them pay?+- Price sensitivity indicators++## 4. Feature Requests / Opportunities+- What features do people wish existed?+- What would make existing solutions better?++## 5. Marketing Insights+- What messaging resonates?+- Where do these users hang out?+- What objections would they have?++## 6. Key Quotes+- Extract 3-5 verbatim quotes that capture valuable insights++## 7. Actionable Recommendations+- Based on this thread, what product/feature should be built?+- How should it be marketed to this audience?++---++THREAD DATA:+"""+++if __name__ == '__main__':+ if len(sys.argv) < 2:+ print("Usage: python reddit_extractor.py <reddit_url> [--json] [--prompt]")+ sys.exit(1)++ url = sys.argv[1]+ output_json = '--json' in sys.argv+ include_prompt = '--prompt' in sys.argv++ try:+ data = structure_for_analysis(url)++ if output_json:+ print(json.dumps(data, indent=2, default=str))+ else:+ formatted = format_for_llm(data)+ if include_prompt:+ print(ANALYSIS_PROMPT)+ print(formatted)++ except Exception as e:+ print(f"Error: {e}", file=sys.stderr)+ sys.exit(1)diff --git a/agents/reddit-research/src/agent/analyzer.ts b/agents/reddit-research/src/agent/analyzer.tsnew file mode 100644index 0000000..a04aee9--- /dev/null+++ b/agents/reddit-research/src/agent/analyzer.ts@@ -0,0 +1,196 @@+/**+ * Thread Analyzer using Claude+ * Extracts market research insights from Reddit threads+ */++import Anthropic from '@anthropic-ai/sdk';+import type { ThreadData, MarketInsight, PainPoint, Opportunity, CompetitorMention, BuyingSignal, KeyQuote } from '../types.js';++const ANALYSIS_PROMPT = `You are a market research analyst. Analyze this Reddit thread and extract actionable business insights.++Return your analysis as JSON with this exact structure:+{+ "painPoints": [+ {+ "description": "Brief description of the pain point",+ "frequency": 1-10 (how often mentioned),+ "sentiment": "frustrated" | "annoyed" | "desperate" | "neutral",+ "quotes": ["exact quote 1", "exact quote 2"]+ }+ ],+ "opportunities": [+ {+ "description": "Product/feature/service opportunity",+ "type": "product" | "feature" | "service" | "content",+ "confidence": "high" | "medium" | "low",+ "targetAudience": "Who would buy this"+ }+ ],+ "competitorMentions": [+ {+ "name": "Product/Company name",+ "sentiment": "positive" | "negative" | "neutral",+ "context": "Why they mentioned it",+ "frequency": 1+ }+ ],+ "buyingSignals": [+ {+ "quote": "Exact quote showing buying intent",+ "author": "username",+ "signalType": "looking" | "considering" | "ready" | "switched",+ "score": comment_score+ }+ ],+ "keyQuotes": [+ {+ "text": "Insightful quote",+ "author": "username",+ "score": comment_score,+ "insightType": "pain_point" | "opportunity" | "competitor" | "general"+ }+ ],+ "summary": "2-3 sentence summary of key insights and opportunities"+}++Focus on:+1. Real pain points people are experiencing+2. Products/features they wish existed+3. Competitors mentioned (positively or negatively)+4. Buying signals (looking for, considering, switched to)+5. High-engagement comments (high score = resonates with community)++THREAD DATA:+`;++/**+ * Format thread for analysis+ */+function formatThreadForAnalysis(data: ThreadData): string {+ const { post, metrics, topComments } = data;++ let content = `# ${post.title}\n\n`;+ content += `**Subreddit:** r/${post.subreddit}\n`;+ content += `**Score:** ${post.score} | **Upvote Ratio:** ${Math.round(post.upvoteRatio * 100)}%\n`;+ content += `**Comments:** ${metrics.totalComments} | **Unique Authors:** ${metrics.uniqueAuthors}\n\n`;++ content += `## Original Post\n\n${post.selftext || '*No content*'}\n\n`;++ content += `## Top Comments (${topComments.length})\n\n`;++ for (const comment of topComments) {+ const indent = ' '.repeat(comment.depth);+ content += `${indent}### [${comment.score} pts] u/${comment.author}\n`;+ content += `${indent}${comment.body.slice(0, 600)}${comment.body.length > 600 ? '...' : ''}\n\n`;+ }++ return content;+}++/**+ * Analyze a thread using Claude+ */+export async function analyzeThread(+ data: ThreadData,+ options: { apiKey?: string } = {}+): Promise<MarketInsight> {+ const client = new Anthropic({+ apiKey: options.apiKey || process.env.ANTHROPIC_API_KEY,+ });++ const threadContent = formatThreadForAnalysis(data);++ const response = await client.messages.create({+ model: 'claude-sonnet-4-20250514',+ max_tokens: 4096,+ messages: [+ {+ role: 'user',+ content: ANALYSIS_PROMPT + threadContent,+ },+ ],+ });++ // Extract JSON from response+ const responseText = response.content[0].type === 'text' ? response.content[0].text : '';++ // Find JSON in response (may be wrapped in markdown code block)+ const jsonMatch = responseText.match(/\{[\s\S]*\}/);+ if (!jsonMatch) {+ throw new Error('Failed to extract JSON from Claude response');+ }++ const analysis = JSON.parse(jsonMatch[0]);++ return {+ id: crypto.randomUUID(),+ threadUrl: data.post.url,+ subreddit: data.post.subreddit,+ extractedAt: new Date().toISOString(),+ painPoints: analysis.painPoints || [],+ opportunities: analysis.opportunities || [],+ competitorMentions: analysis.competitorMentions || [],+ buyingSignals: analysis.buyingSignals || [],+ keyQuotes: analysis.keyQuotes || [],+ summary: analysis.summary || '',+ };+}++/**+ * Quick analysis without Claude (pattern matching)+ */+export function quickAnalyze(data: ThreadData): Partial<MarketInsight> {+ const allText = [+ data.post.title,+ data.post.selftext,+ ...data.allComments.map(c => c.body),+ ].join('\n').toLowerCase();++ // Pattern-based competitor detection+ const competitorPatterns = [+ /canva/gi, /figma/gi, /notion/gi, /slack/gi, /shopify/gi,+ /stripe/gi, /mailchimp/gi, /hubspot/gi, /salesforce/gi,+ /airtable/gi, /zapier/gi, /vercel/gi, /supabase/gi,+ ];++ const competitors: CompetitorMention[] = [];+ for (const pattern of competitorPatterns) {+ const matches = allText.match(pattern);+ if (matches) {+ competitors.push({+ name: matches[0],+ sentiment: 'neutral',+ context: 'Mentioned in discussion',+ frequency: matches.length,+ });+ }+ }++ // Pattern-based buying signals+ const buyingPatterns = [+ { pattern: /looking for|searching for|need a/gi, type: 'looking' as const },+ { pattern: /considering|thinking about|might try/gi, type: 'considering' as const },+ { pattern: /just bought|just purchased|signed up for/gi, type: 'ready' as const },+ { pattern: /switched from|moved from|replaced/gi, type: 'switched' as const },+ ];++ const signals: BuyingSignal[] = [];+ for (const comment of data.topComments.slice(0, 10)) {+ for (const { pattern, type } of buyingPatterns) {+ if (pattern.test(comment.body)) {+ signals.push({+ quote: comment.body.slice(0, 200),+ author: comment.author,+ signalType: type,+ score: comment.score,+ });+ break;+ }+ }+ }++ return {+ competitorMentions: competitors,+ buyingSignals: signals,+ };+}diff --git a/agents/reddit-research/src/agent/index.ts b/agents/reddit-research/src/agent/index.tsnew file mode 100644index 0000000..778f75f--- /dev/null+++ b/agents/reddit-research/src/agent/index.ts@@ -0,0 +1,148 @@+/**+ * Reddit Research Agent - Main Entry Point+ */++import { runScanCycle, startScheduledAgent, printStats } from './runner.js';+import { initDatabase, addTrackedSource, getTrackedSources } from '../db/index.js';+import { startDashboard } from '../dashboard/index.js';+import { createMultiAgentScanner } from './multiAgent.js';++async function main() {+ const args = process.argv.slice(2);+ const command = args[0] || 'run';++ console.log('π Reddit Research Agent\n');++ switch (command) {+ case 'run':+ // Run a single scan cycle+ console.log('Running single scan cycle...\n');+ const result = await runScanCycle({ verbose: true });+ console.log(`\nβ Complete! Scanned ${result.threadsScanned} threads, found ${result.insightsFound} insights.`);+ break;++ case 'schedule':+ // Start scheduled agent+ const schedule = args[1] || '0 9 * * *';+ console.log(`Starting scheduled agent (${schedule})...\n`);+ startScheduledAgent(schedule, { verbose: true });+ break;++ case 'stats':+ // Print stats+ initDatabase();+ printStats();+ break;++ case 'add':+ // Add a tracked source+ const subreddit = args[1];+ const query = args[2];+ if (!subreddit) {+ console.log('Usage: agent add <subreddit> [query]');+ process.exit(1);+ }+ initDatabase();+ addTrackedSource(subreddit, query);+ console.log(`β Added: r/${subreddit}${query ? ` (query: "${query}")` : ''}`);+ break;++ case 'sources':+ // List tracked sources+ initDatabase();+ const sources = getTrackedSources();+ console.log('Tracked Sources:\n');+ for (const source of sources) {+ console.log(` r/${source.subreddit}${source.query ? ` - "${source.query}"` : ''}`);+ if (source.lastScanned) {+ console.log(` Last scanned: ${source.lastScanned}`);+ }+ }+ if (sources.length === 0) {+ console.log(' No sources configured. Run: agent add <subreddit>');+ }+ break;++ case 'dashboard':+ // Start web dashboard+ const dashboardPort = parseInt(args[1] || '3456', 10);+ console.log(`Starting dashboard on port ${dashboardPort}...\n`);+ initDatabase();+ startDashboard(dashboardPort);+ break;++ case 'parallel':+ // Run multi-agent parallel scan+ const subredditsArg = args[1];+ if (!subredditsArg) {+ console.log('Usage: agent parallel <subreddits> [--queries <queries>]');+ console.log('Example: agent parallel "SaaS,entrepreneur,smallbusiness" --queries "wish existed,looking for"');+ process.exit(1);+ }+ const subreddits = subredditsArg.split(',').map(s => s.trim()).filter(Boolean);+ if (subreddits.length === 0) {+ console.log('Error: No valid subreddits provided');+ process.exit(1);+ }+ const queriesFlag = args.indexOf('--queries');+ const queries = queriesFlag > -1 && args[queriesFlag + 1]+ ? args[queriesFlag + 1].split(',').map(q => q.trim()).filter(Boolean)+ : undefined;++ console.log(`Starting parallel scan of ${subreddits.length} subreddits...\n`);+ initDatabase();+ const scanner = createMultiAgentScanner({ maxConcurrency: 3, verbose: true });+ const results = await scanner.scanSubreddits(subreddits, { queries, useClaudeAnalysis: false });+ const stats = scanner.getAggregatedStats(results);++ console.log('\nπ Parallel Scan Complete\n');+ console.log(`Total Threads: ${stats.totalThreads}`);+ console.log(`Total Insights: ${stats.totalInsights}`);+ console.log(`Duration: ${Math.round(stats.totalDuration / 1000)}s`);+ console.log('\nBy Subreddit:');+ for (const [sub, data] of Object.entries(stats.bySubreddit)) {+ console.log(` r/${sub}: ${data.threads} threads, ${data.insights} insights`);+ }+ console.log('\nTop 5 Threads:');+ for (const thread of stats.topThreads.slice(0, 5)) {+ console.log(` [${thread.goldmineScore}] ${thread.title.slice(0, 50)}...`);+ }+ break;++ case 'help':+ default:+ console.log(`+Usage: npx tsx src/agent/index.ts <command>++Commands:+ run Run a single scan cycle (default)+ schedule Start scheduled agent (runs daily at 9 AM)+ stats Show database statistics+ add Add a tracked subreddit: add <subreddit> [query]+ sources List tracked sources+ dashboard Start web dashboard to explore insights+ parallel Run parallel scan of multiple subreddits+ help Show this help++Examples:+ npx tsx src/agent/index.ts run+ npx tsx src/agent/index.ts schedule "0 */6 * * *" # Every 6 hours+ npx tsx src/agent/index.ts add SaaS "wish existed"+ npx tsx src/agent/index.ts add entrepreneur+ npx tsx src/agent/index.ts dashboard 8080+ npx tsx src/agent/index.ts parallel "SaaS,entrepreneur" --queries "wish existed,looking for"++Environment Variables:+ ANTHROPIC_API_KEY - Enable Claude analysis+ SLACK_WEBHOOK_URL - Enable Slack alerts+ EMAIL_API_KEY - Enable email alerts (Resend or SendGrid)+ EMAIL_PROVIDER - Email provider (resend or sendgrid)+ EMAIL_FROM - Sender email address+ EMAIL_TO - Recipient email address+ NOTION_API_KEY - Enable Notion sync+ NOTION_DATABASE_ID - Notion database for threads+`);+ }+}++main().catch(console.error);diff --git a/agents/reddit-research/src/agent/multiAgent.ts b/agents/reddit-research/src/agent/multiAgent.tsnew file mode 100644index 0000000..11e5bf7--- /dev/null+++ b/agents/reddit-research/src/agent/multiAgent.ts@@ -0,0 +1,249 @@+/**+ * Multi-Agent Parallel Scanning+ * Run multiple scanners concurrently for faster research+ */++import { findGoldmineThreads, fetchThread, searchSubreddit } from '../reddit/index.js';+import { analyzeThread, quickAnalyze } from './analyzer.js';+import { getRedditRateLimiter, retryWithBackoff } from '../utils/rateLimiter.js';+import type { GoldmineScore, MarketInsight } from '../types.js';++export interface ScanTask {+ id: string;+ subreddit: string;+ query?: string;+ maxThreads?: number;+ useClaudeAnalysis?: boolean;+}++export interface ScanResult {+ taskId: string;+ subreddit: string;+ query?: string;+ threads: GoldmineScore[];+ insights: MarketInsight[];+ errors: string[];+ duration: number;+}++/**+ * Worker function to scan a single subreddit+ */+async function scanSubredditWorker(task: ScanTask): Promise<ScanResult> {+ const startTime = Date.now();+ const rateLimiter = getRedditRateLimiter();+ const result: ScanResult = {+ taskId: task.id,+ subreddit: task.subreddit,+ query: task.query,+ threads: [],+ insights: [],+ errors: [],+ duration: 0+ };++ try {+ // Find goldmine threads with rate limiting+ await rateLimiter.acquireWithBackoff();++ const threads = task.query+ ? await retryWithBackoff(() => searchSubreddit(task.subreddit, task.query!, { limit: task.maxThreads || 20 }))+ : await retryWithBackoff(() => findGoldmineThreads(task.subreddit));++ rateLimiter.reportSuccess();+ result.threads = threads;++ // Analyze top threads+ const threadsToAnalyze = threads+ .filter(t => t.goldmineScore >= 15)+ .slice(0, 5);++ for (const thread of threadsToAnalyze) {+ try {+ await rateLimiter.acquireWithBackoff();+ const threadData = await retryWithBackoff(() => fetchThread(thread.url));+ rateLimiter.reportSuccess();++ let insight: MarketInsight | null = null;++ if (task.useClaudeAnalysis && process.env.ANTHROPIC_API_KEY) {+ insight = await analyzeThread(threadData);+ } else {+ // Quick analysis fallback+ const quick = quickAnalyze(threadData);+ insight = {+ id: crypto.randomUUID(),+ threadUrl: thread.url,+ subreddit: thread.subreddit,+ extractedAt: new Date().toISOString(),+ painPoints: [],+ opportunities: [],+ competitorMentions: quick.competitorMentions || [],+ buyingSignals: quick.buyingSignals || [],+ keyQuotes: [],+ summary: `Quick analysis of ${thread.title.slice(0, 50)}...`+ };+ }++ if (insight) {+ result.insights.push(insight);+ }+ } catch (error) {+ result.errors.push(`Failed to analyze ${thread.url}: ${error}`);+ rateLimiter.reportError();+ }+ }+ } catch (error) {+ result.errors.push(`Failed to scan r/${task.subreddit}: ${error}`);+ rateLimiter.reportError();+ }++ result.duration = Date.now() - startTime;+ return result;+}++/**+ * Multi-Agent Scanner+ * Coordinates parallel scanning of multiple subreddits+ */+export class MultiAgentScanner {+ private maxConcurrency: number;+ private verbose: boolean;++ constructor(options: { maxConcurrency?: number; verbose?: boolean } = {}) {+ this.maxConcurrency = options.maxConcurrency || 3;+ this.verbose = options.verbose ?? false;+ }++ /**+ * Run tasks in parallel with concurrency limit+ */+ async runParallel(tasks: ScanTask[]): Promise<ScanResult[]> {+ const results: ScanResult[] = [];+ const queue = [...tasks];+ const running: Promise<void>[] = [];++ const runTask = async (task: ScanTask): Promise<void> => {+ if (this.verbose) {+ console.log(`[Agent] Starting scan: r/${task.subreddit}${task.query ? ` "${task.query}"` : ''}`);+ }++ const result = await scanSubredditWorker(task);+ results.push(result);++ if (this.verbose) {+ console.log(`[Agent] Completed: r/${task.subreddit} - ${result.threads.length} threads, ${result.insights.length} insights (${result.duration}ms)`);+ if (result.errors.length > 0) {+ console.log(`[Agent] Errors: ${result.errors.length}`);+ }+ }+ };++ // Process queue with concurrency limit+ while (queue.length > 0 || running.length > 0) {+ // Start new tasks up to concurrency limit+ while (running.length < this.maxConcurrency && queue.length > 0) {+ const task = queue.shift()!;+ const promise = runTask(task).then(() => {+ const index = running.indexOf(promise);+ if (index > -1) running.splice(index, 1);+ });+ running.push(promise);+ }++ // Wait for at least one to complete+ if (running.length > 0) {+ await Promise.race(running);+ }+ }++ return results;+ }++ /**+ * Scan multiple subreddits+ */+ async scanSubreddits(+ subreddits: string[],+ options: { queries?: string[]; useClaudeAnalysis?: boolean } = {}+ ): Promise<ScanResult[]> {+ const tasks: ScanTask[] = [];++ for (const subreddit of subreddits) {+ if (options.queries && options.queries.length > 0) {+ // Create task for each query+ for (const query of options.queries) {+ tasks.push({+ id: `${subreddit}-${query}`,+ subreddit,+ query,+ useClaudeAnalysis: options.useClaudeAnalysis+ });+ }+ } else {+ // Single task without query+ tasks.push({+ id: subreddit,+ subreddit,+ useClaudeAnalysis: options.useClaudeAnalysis+ });+ }+ }++ return this.runParallel(tasks);+ }++ /**+ * Get aggregated stats from results+ */+ getAggregatedStats(results: ScanResult[]): {+ totalThreads: number;+ totalInsights: number;+ totalErrors: number;+ totalDuration: number;+ bySubreddit: Record<string, { threads: number; insights: number }>;+ topThreads: GoldmineScore[];+ } {+ const stats = {+ totalThreads: 0,+ totalInsights: 0,+ totalErrors: 0,+ totalDuration: 0,+ bySubreddit: {} as Record<string, { threads: number; insights: number }>,+ topThreads: [] as GoldmineScore[]+ };++ for (const result of results) {+ stats.totalThreads += result.threads.length;+ stats.totalInsights += result.insights.length;+ stats.totalErrors += result.errors.length;+ stats.totalDuration = Math.max(stats.totalDuration, result.duration);++ stats.bySubreddit[result.subreddit] = stats.bySubreddit[result.subreddit] || { threads: 0, insights: 0 };+ stats.bySubreddit[result.subreddit].threads += result.threads.length;+ stats.bySubreddit[result.subreddit].insights += result.insights.length;++ stats.topThreads.push(...result.threads);+ }++ // Sort and dedupe top threads+ const seenUrls = new Set<string>();+ stats.topThreads = stats.topThreads+ .filter(t => {+ if (seenUrls.has(t.url)) return false;+ seenUrls.add(t.url);+ return true;+ })+ .sort((a, b) => b.goldmineScore - a.goldmineScore)+ .slice(0, 50);++ return stats;+ }+}++/**+ * Create multi-agent scanner+ */+export function createMultiAgentScanner(options?: { maxConcurrency?: number; verbose?: boolean }): MultiAgentScanner {+ return new MultiAgentScanner(options);+}diff --git a/agents/reddit-research/src/agent/runner.ts b/agents/reddit-research/src/agent/runner.tsnew file mode 100644index 0000000..bfa6ec4--- /dev/null+++ b/agents/reddit-research/src/agent/runner.ts@@ -0,0 +1,315 @@+/**+ * Reddit Research Agent Runner+ * Orchestrates the scanning, analysis, and storage pipeline+ */++import cron from 'node-cron';+import { findGoldmineThreads, fetchThread, searchSubreddit } from '../reddit/index.js';+import { analyzeThread, quickAnalyze } from './analyzer.js';+import {+ initDatabase,+ saveThreads,+ getUnanalyzedThreads,+ markThreadAnalyzed,+ saveInsight,+ startAgentRun,+ completeAgentRun,+ failAgentRun,+ getTrackedSources,+ addTrackedSource,+ updateSourceScanned,+ getStats,+} from '../db/index.js';+import { AlertManager, createAlertManager } from '../alerts/index.js';+import { NotionSync, createNotionSync } from '../sync/index.js';+import { getRedditRateLimiter, retryWithBackoff } from '../utils/rateLimiter.js';+import type { ScanConfig, GoldmineScore, MarketInsight } from '../types.js';++export interface AgentOptions {+ dbPath?: string;+ maxThreadsPerScan?: number;+ minGoldmineScore?: number;+ useClaudeAnalysis?: boolean;+ verbose?: boolean;+ enableAlerts?: boolean;+ enableNotionSync?: boolean;+ alertThreshold?: number; // Goldmine score threshold for alerts+}++const DEFAULT_OPTIONS: Required<AgentOptions> = {+ dbPath: './reddit-research.db',+ maxThreadsPerScan: 20,+ minGoldmineScore: 15,+ useClaudeAnalysis: true,+ verbose: true,+ enableAlerts: true,+ enableNotionSync: true,+ alertThreshold: 25, // Only alert on high-value threads+};++/**+ * Log with timestamp if verbose+ */+function log(message: string, verbose: boolean): void {+ if (verbose) {+ console.log(`[${new Date().toISOString()}] ${message}`);+ }+}++/**+ * Run a single scan cycle+ */+export async function runScanCycle(options: AgentOptions = {}): Promise<{+ threadsScanned: number;+ insightsFound: number;+ costUsd: number;+}> {+ const opts = { ...DEFAULT_OPTIONS, ...options };+ const startTime = Date.now();+ const rateLimiter = getRedditRateLimiter();++ // Initialize services+ initDatabase(opts.dbPath);+ const runId = startAgentRun();++ // Initialize optional services+ const alertManager = opts.enableAlerts ? createAlertManager({ verbose: opts.verbose }) : null;+ const notionSync = opts.enableNotionSync ? createNotionSync({ verbose: opts.verbose }) : null;++ log('Starting scan cycle...', opts.verbose);+ if (alertManager?.isConfigured()) {+ log('Alerts enabled', opts.verbose);+ }+ if (notionSync?.isConfigured()) {+ log('Notion sync enabled', opts.verbose);+ }++ let threadsScanned = 0;+ let insightsFound = 0;+ let costUsd = 0;+ const highValueThreads: GoldmineScore[] = [];++ try {+ // Get tracked sources+ let sources = getTrackedSources();++ // Add defaults if no sources configured+ if (sources.length === 0) {+ log('No tracked sources. Adding defaults...', opts.verbose);+ addTrackedSource('SaaS');+ addTrackedSource('smallbusiness');+ addTrackedSource('entrepreneur');+ sources = getTrackedSources();+ }++ // Scan each source with rate limiting+ for (const source of sources) {+ log(`Scanning r/${source.subreddit}${source.query ? ` for "${source.query}"` : ''}...`, opts.verbose);++ try {+ // Apply rate limiting+ await rateLimiter.acquireWithBackoff();++ const threads = await retryWithBackoff(async () => {+ return source.query+ ? await searchSubreddit(source.subreddit, source.query!, { limit: opts.maxThreadsPerScan })+ : await findGoldmineThreads(source.subreddit);+ }, {+ onRetry: (error, attempt) => {+ log(`Retry ${attempt} for ${source.subreddit}: ${error.message}`, opts.verbose);+ rateLimiter.reportError();+ }+ });++ rateLimiter.reportSuccess();++ // Filter by goldmine score+ const goldmineThreads = threads.filter(t => t.goldmineScore >= opts.minGoldmineScore);+ log(`Found ${goldmineThreads.length} goldmine threads (score >= ${opts.minGoldmineScore})`, opts.verbose);++ // Save to database+ saveThreads(goldmineThreads);+ updateSourceScanned(source.subreddit, source.query || undefined);++ threadsScanned += goldmineThreads.length;++ // Track high-value threads for alerts+ const highValue = goldmineThreads.filter(t => t.goldmineScore >= opts.alertThreshold);+ highValueThreads.push(...highValue);++ // Alert on high-value threads immediately+ if (alertManager?.isConfigured()) {+ for (const thread of highValue) {+ await alertManager.alertThread(thread);+ }+ }++ // Sync to Notion+ if (notionSync?.isConfigured() && goldmineThreads.length > 0) {+ await notionSync.syncThreads(goldmineThreads);+ }+ } catch (error) {+ log(`Error scanning ${source.subreddit}: ${error}`, opts.verbose);+ rateLimiter.reportError();+ }+ }++ // Analyze unanalyzed threads+ const unanalyzed = getUnanalyzedThreads(5); // Analyze top 5 at a time+ log(`Analyzing ${unanalyzed.length} threads...`, opts.verbose);++ for (const { id, url, goldmineScore } of unanalyzed) {+ try {+ // Rate limit thread fetching+ await rateLimiter.acquireWithBackoff();++ log(`Fetching thread: ${url}`, opts.verbose);+ const threadData = await retryWithBackoff(() => fetchThread(url), {+ onRetry: (error, attempt) => {+ log(`Retry ${attempt} fetching ${url}: ${error.message}`, opts.verbose);+ rateLimiter.reportError();+ }+ });++ rateLimiter.reportSuccess();++ let insights: Partial<MarketInsight>;++ if (opts.useClaudeAnalysis) {+ log('Analyzing with Claude...', opts.verbose);+ insights = await analyzeThread(threadData);+ costUsd += 0.01; // Rough estimate per analysis+ } else {+ log('Using quick pattern analysis...', opts.verbose);+ insights = quickAnalyze(threadData);+ }++ // Save insights to database+ for (const painPoint of insights.painPoints || []) {+ saveInsight(id, 'pain_point', painPoint.description, {+ frequency: painPoint.frequency,+ sentiment: painPoint.sentiment,+ quotes: painPoint.quotes,+ }, 'medium');+ insightsFound++;+ }++ for (const opportunity of insights.opportunities || []) {+ saveInsight(id, 'opportunity', opportunity.description, {+ type: opportunity.type,+ targetAudience: opportunity.targetAudience,+ }, opportunity.confidence);+ insightsFound++;+ }++ for (const competitor of insights.competitorMentions || []) {+ saveInsight(id, 'competitor', competitor.name, {+ sentiment: competitor.sentiment,+ context: competitor.context,+ frequency: competitor.frequency,+ });+ insightsFound++;+ }++ for (const signal of insights.buyingSignals || []) {+ saveInsight(id, 'buying_signal', signal.quote, {+ author: signal.author,+ signalType: signal.signalType,+ score: signal.score,+ });+ insightsFound++;+ }++ for (const quote of insights.keyQuotes || []) {+ saveInsight(id, 'quote', quote.text, {+ author: quote.author,+ score: quote.score,+ insightType: quote.insightType,+ });+ insightsFound++;+ }++ if (insights.summary) {+ saveInsight(id, 'summary', insights.summary);+ }++ markThreadAnalyzed(id);+ log(`Thread analyzed: ${insightsFound} insights found`, opts.verbose);++ } catch (error) {+ log(`Error analyzing thread ${url}: ${error}`, opts.verbose);+ }+ }++ // Complete the run+ completeAgentRun(runId, { threadsScanned, insightsFound, costUsd });+ const duration = Date.now() - startTime;+ log(`Scan cycle complete. Threads: ${threadsScanned}, Insights: ${insightsFound}, Duration: ${Math.round(duration / 1000)}s`, opts.verbose);++ // Send scan summary alert+ if (alertManager?.isConfigured()) {+ await alertManager.alertScanSummary({+ threadsScanned,+ insightsFound,+ topThreads: highValueThreads.slice(0, 5),+ duration,+ });+ }++ return { threadsScanned, insightsFound, costUsd };++ } catch (error) {+ failAgentRun(runId, String(error));+ throw error;+ }+}++/**+ * Start scheduled agent+ */+export function startScheduledAgent(+ schedule: string = '0 9 * * *', // Daily at 9 AM+ options: AgentOptions = {}+): void {+ const opts = { ...DEFAULT_OPTIONS, ...options };++ log(`Starting scheduled agent with cron: ${schedule}`, opts.verbose);++ // Initialize database+ initDatabase(opts.dbPath);++ // Run immediately on start+ runScanCycle(options).catch(console.error);++ // Schedule future runs+ cron.schedule(schedule, async () => {+ log('Scheduled scan triggered', opts.verbose);+ try {+ await runScanCycle(options);+ } catch (error) {+ console.error('Scheduled scan failed:', error);+ }+ });++ log('Agent started. Press Ctrl+C to stop.', opts.verbose);+}++/**+ * Print agent stats+ */+export function printStats(): void {+ const stats = getStats();++ console.log('\nπ Reddit Research Agent Stats\n');+ console.log(`Threads Scanned: ${stats.totalThreads}`);+ console.log(`Threads Analyzed: ${stats.analyzedThreads}`);+ console.log(`Total Insights: ${stats.totalInsights}`);+ console.log('\nInsights by Type:');+ for (const [type, count] of Object.entries(stats.insightsByType)) {+ console.log(` ${type}: ${count}`);+ }+ console.log('\nTop Subreddits:');+ for (const { subreddit, count } of stats.topSubreddits) {+ console.log(` r/${subreddit}: ${count} threads`);+ }+}diff --git a/agents/reddit-research/src/alerts/email.ts b/agents/reddit-research/src/alerts/email.tsnew file mode 100644index 0000000..8fc057a--- /dev/null+++ b/agents/reddit-research/src/alerts/email.ts@@ -0,0 +1,294 @@+/**+ * Email Alert Integration+ * Sends email notifications for high-value discoveries+ *+ * Uses nodemailer-compatible SMTP or can integrate with services like:+ * - SendGrid+ * - Mailgun+ * - AWS SES+ * - Resend+ */++import { execFileNoThrow } from '../utils/execFileNoThrow.js';+import type { GoldmineScore, MarketInsight } from '../types.js';++/**+ * Escape HTML entities to prevent XSS in emails+ */+function escapeHtml(str: string | undefined | null): string {+ if (!str) return '';+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++export interface EmailConfig {+ to: string;+ from?: string;+ smtpHost?: string;+ smtpPort?: number;+ smtpUser?: string;+ smtpPass?: string;+ // Or use API-based services+ sendgridApiKey?: string;+ resendApiKey?: string;+}++/**+ * Format thread as HTML email+ */+function formatThreadEmail(thread: GoldmineScore): { subject: string; html: string; text: string } {+ const subject = `π Reddit Goldmine: ${thread.title.slice(0, 50)}...`;++ const html = `+<!DOCTYPE html>+<html>+<head>+ <style>+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }+ .header { background: #ff4500; color: white; padding: 20px; border-radius: 8px 8px 0 0; }+ .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }+ .stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin: 20px 0; }+ .stat { background: white; padding: 15px; border-radius: 4px; text-align: center; }+ .stat-value { font-size: 24px; font-weight: bold; color: #ff4500; }+ .stat-label { font-size: 12px; color: #666; }+ .cta { display: inline-block; background: #ff4500; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin-top: 20px; }+ </style>+</head>+<body>+ <div class="header">+ <h1>π High-Value Thread Found!</h1>+ </div>+ <div class="content">+ <h2>${escapeHtml(thread.title)}</h2>+ <p><strong>Subreddit:</strong> r/${escapeHtml(thread.subreddit)}</p>++ <div class="stats">+ <div class="stat">+ <div class="stat-value">${escapeHtml(String(thread.goldmineScore))}</div>+ <div class="stat-label">Goldmine Score</div>+ </div>+ <div class="stat">+ <div class="stat-value">${escapeHtml(String(thread.score))}</div>+ <div class="stat-label">Post Score</div>+ </div>+ <div class="stat">+ <div class="stat-value">${escapeHtml(String(thread.numComments))}</div>+ <div class="stat-label">Comments</div>+ </div>+ <div class="stat">+ <div class="stat-value">${escapeHtml(String(Math.round(thread.upvoteRatio * 100)))}%</div>+ <div class="stat-label">Upvote Ratio</div>+ </div>+ </div>++ <a href="${escapeHtml(thread.url)}" class="cta">View Thread β</a>+ </div>+</body>+</html>+ `.trim();++ const text = `+π HIGH-VALUE THREAD FOUND!++${thread.title}++Subreddit: r/${thread.subreddit}+Goldmine Score: ${thread.goldmineScore}+Post Score: ${thread.score}+Comments: ${thread.numComments}+Upvote Ratio: ${Math.round(thread.upvoteRatio * 100)}%++View: ${thread.url}+ `.trim();++ return { subject, html, text };+}++/**+ * Format insights as HTML email+ */+function formatInsightsEmail(insight: MarketInsight, threadTitle: string): { subject: string; html: string; text: string } {+ const subject = `π Market Insights: ${threadTitle.slice(0, 40)}...`;++ const painPointsHtml = insight.painPoints.length > 0+ ? `<h3>π΄ Pain Points</h3><ul>${insight.painPoints.map(p => `<li><strong>${escapeHtml(p.description)}</strong> (frequency: ${escapeHtml(String(p.frequency))})</li>`).join('')}</ul>`+ : '';++ const opportunitiesHtml = insight.opportunities.length > 0+ ? `<h3>π‘ Opportunities</h3><ul>${insight.opportunities.map(o => `<li><strong>[${escapeHtml(o.confidence)}]</strong> ${escapeHtml(o.description)}<br><small>Target: ${escapeHtml(o.targetAudience)}</small></li>`).join('')}</ul>`+ : '';++ const competitorsHtml = insight.competitorMentions.length > 0+ ? `<h3>π’ Competitors Mentioned</h3><ul>${insight.competitorMentions.map(c => `<li><strong>${escapeHtml(c.name)}</strong> (${escapeHtml(c.sentiment)}) - ${escapeHtml(c.context)}</li>`).join('')}</ul>`+ : '';++ const signalsHtml = insight.buyingSignals.length > 0+ ? `<h3>π° Buying Signals</h3><ul>${insight.buyingSignals.map(s => `<li>"${escapeHtml(s.quote.slice(0, 150))}..." - u/${escapeHtml(s.author)} (${escapeHtml(String(s.score))} pts)</li>`).join('')}</ul>`+ : '';++ const html = `+<!DOCTYPE html>+<html>+<head>+ <style>+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }+ .header { background: #0066cc; color: white; padding: 20px; border-radius: 8px 8px 0 0; }+ .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }+ .summary { background: white; padding: 15px; border-radius: 4px; border-left: 4px solid #0066cc; margin: 20px 0; }+ h3 { color: #333; margin-top: 25px; }+ ul { padding-left: 20px; }+ li { margin: 10px 0; }+ .cta { display: inline-block; background: #0066cc; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin-top: 20px; }+ </style>+</head>+<body>+ <div class="header">+ <h1>π Market Insights Extracted</h1>+ </div>+ <div class="content">+ <p><strong>Thread:</strong> ${escapeHtml(threadTitle)}</p>+ <p><strong>Subreddit:</strong> r/${escapeHtml(insight.subreddit)}</p>++ <div class="summary">+ <strong>Summary:</strong> ${escapeHtml(insight.summary)}+ </div>++ ${painPointsHtml}+ ${opportunitiesHtml}+ ${competitorsHtml}+ ${signalsHtml}++ <a href="${escapeHtml(insight.threadUrl)}" class="cta">View Thread β</a>+ </div>+</body>+</html>+ `.trim();++ const text = `+π MARKET INSIGHTS EXTRACTED++Thread: ${threadTitle}+Subreddit: r/${insight.subreddit}++Summary: ${insight.summary}++Pain Points (${insight.painPoints.length}):+${insight.painPoints.map(p => `- ${p.description}`).join('\n')}++Opportunities (${insight.opportunities.length}):+${insight.opportunities.map(o => `- [${o.confidence}] ${o.description}`).join('\n')}++View: ${insight.threadUrl}+ `.trim();++ return { subject, html, text };+}++/**+ * Send email via Resend API+ */+async function sendViaResend(apiKey: string, to: string, from: string, subject: string, html: string): Promise<boolean> {+ const result = await execFileNoThrow('curl', [+ '-s',+ '-X', 'POST',+ 'https://api.resend.com/emails',+ '-H', `Authorization: Bearer ${apiKey}`,+ '-H', 'Content-Type: application/json',+ '-d', JSON.stringify({ from, to: [to], subject, html })+ ]);++ return result.status === 'success' && result.stdout.includes('"id"');+}++/**+ * Send email via SendGrid API+ */+async function sendViaSendGrid(apiKey: string, to: string, from: string, subject: string, html: string, text: string): Promise<boolean> {+ const result = await execFileNoThrow('curl', [+ '-s',+ '-X', 'POST',+ 'https://api.sendgrid.com/v3/mail/send',+ '-H', `Authorization: Bearer ${apiKey}`,+ '-H', 'Content-Type: application/json',+ '-d', JSON.stringify({+ personalizations: [{ to: [{ email: to }] }],+ from: { email: from },+ subject,+ content: [+ { type: 'text/plain', value: text },+ { type: 'text/html', value: html }+ ]+ })+ ]);++ return result.status === 'success';+}++/**+ * Email Alert Manager+ */+export class EmailAlerts {+ private config: EmailConfig;++ constructor(config: EmailConfig) {+ this.config = {+ from: 'Reddit Research Agent <[email protected]>',+ ...config+ };+ }++ /**+ * Send email using configured provider+ */+ private async sendEmail(subject: string, html: string, text: string): Promise<boolean> {+ const { to, from, resendApiKey, sendgridApiKey } = this.config;++ if (resendApiKey) {+ return sendViaResend(resendApiKey, to, from || '[email protected]', subject, html);+ }++ if (sendgridApiKey) {+ return sendViaSendGrid(sendgridApiKey, to, from || '[email protected]', subject, html, text);+ }++ console.warn('No email provider configured. Set RESEND_API_KEY or SENDGRID_API_KEY.');+ return false;+ }++ /**+ * Alert on high-value thread+ */+ async alertThread(thread: GoldmineScore): Promise<boolean> {+ const { subject, html, text } = formatThreadEmail(thread);+ return this.sendEmail(subject, html, text);+ }++ /**+ * Alert on new insights+ */+ async alertInsights(insight: MarketInsight, threadTitle: string): Promise<boolean> {+ const { subject, html, text } = formatInsightsEmail(insight, threadTitle);+ return this.sendEmail(subject, html, text);+ }+}++/**+ * Create email alerts from environment+ */+export function createEmailAlerts(): EmailAlerts | null {+ const to = process.env.ALERT_EMAIL_TO;+ if (!to) {+ return null;+ }++ return new EmailAlerts({+ to,+ from: process.env.ALERT_EMAIL_FROM,+ resendApiKey: process.env.RESEND_API_KEY,+ sendgridApiKey: process.env.SENDGRID_API_KEY+ });+}diff --git a/agents/reddit-research/src/alerts/index.ts b/agents/reddit-research/src/alerts/index.tsnew file mode 100644index 0000000..5b3b2fb--- /dev/null+++ b/agents/reddit-research/src/alerts/index.ts@@ -0,0 +1,105 @@+/**+ * Alert System+ * Unified interface for Slack and Email alerts+ */++export * from './slack.js';+export * from './email.js';++import { SlackAlerts, createSlackAlerts } from './slack.js';+import { EmailAlerts, createEmailAlerts } from './email.js';+import type { GoldmineScore, MarketInsight } from '../types.js';++/**+ * Unified Alert Manager+ * Sends alerts to all configured channels+ */+export class AlertManager {+ private slack: SlackAlerts | null;+ private email: EmailAlerts | null;+ private verbose: boolean;++ constructor(options: { verbose?: boolean } = {}) {+ this.slack = createSlackAlerts();+ this.email = createEmailAlerts();+ this.verbose = options.verbose ?? false;++ if (this.verbose) {+ console.log(`Alerts configured: Slack=${!!this.slack}, Email=${!!this.email}`);+ }+ }++ /**+ * Check if any alerts are configured+ */+ isConfigured(): boolean {+ return this.slack !== null || this.email !== null;+ }++ /**+ * Alert on high-value thread discovery+ */+ async alertThread(thread: GoldmineScore): Promise<void> {+ const promises: Promise<boolean>[] = [];++ if (this.slack) {+ promises.push(this.slack.alertThread(thread));+ }++ if (this.email) {+ promises.push(this.email.alertThread(thread));+ }++ if (promises.length > 0) {+ const results = await Promise.allSettled(promises);+ if (this.verbose) {+ const succeeded = results.filter(r => r.status === 'fulfilled' && r.value).length;+ console.log(`Thread alert sent to ${succeeded}/${promises.length} channels`);+ }+ }+ }++ /**+ * Alert on new market insights+ */+ async alertInsights(insight: MarketInsight, threadTitle: string): Promise<void> {+ const promises: Promise<boolean>[] = [];++ if (this.slack) {+ promises.push(this.slack.alertInsights(insight, threadTitle));+ }++ if (this.email) {+ promises.push(this.email.alertInsights(insight, threadTitle));+ }++ if (promises.length > 0) {+ const results = await Promise.allSettled(promises);+ if (this.verbose) {+ const succeeded = results.filter(r => r.status === 'fulfilled' && r.value).length;+ console.log(`Insights alert sent to ${succeeded}/${promises.length} channels`);+ }+ }+ }++ /**+ * Alert scan summary (Slack only)+ */+ async alertScanSummary(stats: {+ threadsScanned: number;+ insightsFound: number;+ topThreads: GoldmineScore[];+ duration: number;+ }): Promise<void> {+ if (this.slack) {+ await this.slack.alertScanSummary(stats);+ }+ }+}++/**+ * Create alert manager from environment+ */+export function createAlertManager(options: { verbose?: boolean } = {}): AlertManager {+ return new AlertManager(options);+}diff --git a/agents/reddit-research/src/alerts/slack.ts b/agents/reddit-research/src/alerts/slack.tsnew file mode 100644index 0000000..d253077--- /dev/null+++ b/agents/reddit-research/src/alerts/slack.ts@@ -0,0 +1,277 @@+/**+ * Slack Alert Integration+ * Sends notifications when high-value threads or insights are found+ */++import { execFileNoThrow } from '../utils/execFileNoThrow.js';+import type { GoldmineScore, MarketInsight } from '../types.js';++export interface SlackConfig {+ webhookUrl: string;+ channel?: string;+ username?: string;+ iconEmoji?: string;+ minGoldmineScore?: number;+}++interface SlackMessage {+ text?: string;+ blocks?: SlackBlock[];+ channel?: string;+ username?: string;+ icon_emoji?: string;+}++interface SlackBlock {+ type: string;+ text?: { type: string; text: string; emoji?: boolean };+ fields?: Array<{ type: string; text: string }>;+ elements?: Array<{ type: string; text: string }>;+}++/**+ * Send a message to Slack+ */+async function sendSlackMessage(webhookUrl: string, message: SlackMessage): Promise<boolean> {+ const result = await execFileNoThrow('curl', [+ '-s',+ '-X', 'POST',+ '-H', 'Content-Type: application/json',+ '-d', JSON.stringify(message),+ webhookUrl+ ]);++ return result.status === 'success' && result.stdout === 'ok';+}++/**+ * Format a goldmine thread for Slack+ */+function formatThreadAlert(thread: GoldmineScore): SlackMessage {+ return {+ blocks: [+ {+ type: 'header',+ text: {+ type: 'plain_text',+ text: 'π High-Value Thread Found!',+ emoji: true+ }+ },+ {+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*<${thread.url}|${thread.title.slice(0, 100)}${thread.title.length > 100 ? '...' : ''}>*`+ }+ },+ {+ type: 'section',+ fields: [+ { type: 'mrkdwn', text: `*Subreddit:*\nr/${thread.subreddit}` },+ { type: 'mrkdwn', text: `*Goldmine Score:*\n${thread.goldmineScore}` },+ { type: 'mrkdwn', text: `*Post Score:*\n${thread.score} pts` },+ { type: 'mrkdwn', text: `*Comments:*\n${thread.numComments}` }+ ]+ },+ {+ type: 'context',+ elements: [+ { type: 'mrkdwn', text: `Upvote ratio: ${Math.round(thread.upvoteRatio * 100)}%` }+ ]+ }+ ]+ };+}++/**+ * Format market insights for Slack+ */+function formatInsightAlert(insight: MarketInsight, threadTitle: string): SlackMessage {+ const blocks: SlackBlock[] = [+ {+ type: 'header',+ text: {+ type: 'plain_text',+ text: 'π New Market Insights Extracted!',+ emoji: true+ }+ },+ {+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*Thread:* <${insight.threadUrl}|${threadTitle.slice(0, 80)}...>\n*Summary:* ${insight.summary}`+ }+ }+ ];++ // Pain points+ if (insight.painPoints.length > 0) {+ blocks.push({+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*π΄ Pain Points (${insight.painPoints.length}):*\n${insight.painPoints.slice(0, 3).map(p => `β’ ${p.description}`).join('\n')}`+ }+ });+ }++ // Opportunities+ if (insight.opportunities.length > 0) {+ blocks.push({+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*π‘ Opportunities (${insight.opportunities.length}):*\n${insight.opportunities.slice(0, 3).map(o => `β’ [${o.confidence}] ${o.description}`).join('\n')}`+ }+ });+ }++ // Buying signals+ if (insight.buyingSignals.length > 0) {+ blocks.push({+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*π° Buying Signals (${insight.buyingSignals.length}):*\n${insight.buyingSignals.slice(0, 2).map(s => `β’ "${s.quote.slice(0, 100)}..."`).join('\n')}`+ }+ });+ }++ return { blocks };+}++/**+ * Format scan summary for Slack+ */+function formatScanSummary(stats: {+ threadsScanned: number;+ insightsFound: number;+ topThreads: GoldmineScore[];+ duration: number;+}): SlackMessage {+ return {+ blocks: [+ {+ type: 'header',+ text: {+ type: 'plain_text',+ text: 'β Scan Cycle Complete',+ emoji: true+ }+ },+ {+ type: 'section',+ fields: [+ { type: 'mrkdwn', text: `*Threads Scanned:*\n${stats.threadsScanned}` },+ { type: 'mrkdwn', text: `*Insights Found:*\n${stats.insightsFound}` },+ { type: 'mrkdwn', text: `*Duration:*\n${Math.round(stats.duration / 1000)}s` },+ { type: 'mrkdwn', text: `*Top Score:*\n${stats.topThreads[0]?.goldmineScore || 'N/A'}` }+ ]+ },+ {+ type: 'section',+ text: {+ type: 'mrkdwn',+ text: `*Top Threads:*\n${stats.topThreads.slice(0, 3).map((t, i) => `${i + 1}. <${t.url}|${t.title.slice(0, 50)}...>`).join('\n')}`+ }+ }+ ]+ };+}++/**+ * Slack Alert Manager+ */+export class SlackAlerts {+ private config: SlackConfig;++ constructor(config: SlackConfig) {+ this.config = {+ minGoldmineScore: 25,+ username: 'Reddit Research Agent',+ iconEmoji: ':mag:',+ ...config+ };+ }++ /**+ * Alert on high-value thread+ */+ async alertThread(thread: GoldmineScore): Promise<boolean> {+ if (thread.goldmineScore < (this.config.minGoldmineScore || 25)) {+ return false;+ }++ const message = formatThreadAlert(thread);+ message.username = this.config.username;+ message.icon_emoji = this.config.iconEmoji;+ if (this.config.channel) {+ message.channel = this.config.channel;+ }++ return sendSlackMessage(this.config.webhookUrl, message);+ }++ /**+ * Alert on new insights+ */+ async alertInsights(insight: MarketInsight, threadTitle: string): Promise<boolean> {+ const message = formatInsightAlert(insight, threadTitle);+ message.username = this.config.username;+ message.icon_emoji = this.config.iconEmoji;+ if (this.config.channel) {+ message.channel = this.config.channel;+ }++ return sendSlackMessage(this.config.webhookUrl, message);+ }++ /**+ * Alert scan summary+ */+ async alertScanSummary(stats: {+ threadsScanned: number;+ insightsFound: number;+ topThreads: GoldmineScore[];+ duration: number;+ }): Promise<boolean> {+ const message = formatScanSummary(stats);+ message.username = this.config.username;+ message.icon_emoji = this.config.iconEmoji;+ if (this.config.channel) {+ message.channel = this.config.channel;+ }++ return sendSlackMessage(this.config.webhookUrl, message);+ }++ /**+ * Send custom message+ */+ async sendMessage(text: string): Promise<boolean> {+ return sendSlackMessage(this.config.webhookUrl, {+ text,+ username: this.config.username,+ icon_emoji: this.config.iconEmoji,+ channel: this.config.channel+ });+ }+}++/**+ * Create Slack alerts from environment+ */+export function createSlackAlerts(): SlackAlerts | null {+ const webhookUrl = process.env.SLACK_WEBHOOK_URL;+ if (!webhookUrl) {+ return null;+ }++ return new SlackAlerts({+ webhookUrl,+ channel: process.env.SLACK_CHANNEL,+ minGoldmineScore: parseInt(process.env.SLACK_MIN_SCORE || '25', 10)+ });+}diff --git a/agents/reddit-research/src/dashboard/index.ts b/agents/reddit-research/src/dashboard/index.tsnew file mode 100644index 0000000..3693f48--- /dev/null+++ b/agents/reddit-research/src/dashboard/index.ts@@ -0,0 +1 @@+export * from './server.js';diff --git a/agents/reddit-research/src/dashboard/server.ts b/agents/reddit-research/src/dashboard/server.tsnew file mode 100644index 0000000..b9d6a8e--- /dev/null+++ b/agents/reddit-research/src/dashboard/server.ts@@ -0,0 +1,444 @@+/**+ * Web Dashboard Server+ * Simple HTTP server to explore insights+ */++import { createServer, IncomingMessage, ServerResponse } from 'http';+import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import {+ initDatabase,+ getStats,+ getInsightsByType,+ getUnanalyzedThreads,+ getRecentRuns,+ getTrackedSources+} from '../db/index.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++/**+ * Escape HTML entities to prevent XSS+ */+function escapeHtml(str: string | undefined | null): string {+ if (!str) return '';+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++/**+ * Generate HTML dashboard+ */+function generateDashboard(): string {+ const stats = getStats();+ const recentRuns = getRecentRuns(5);+ const sources = getTrackedSources();+ const painPoints = getInsightsByType('pain_point', 10);+ const opportunities = getInsightsByType('opportunity', 10);+ const competitors = getInsightsByType('competitor', 10);+ const signals = getInsightsByType('buying_signal', 10);+ const unanalyzed = getUnanalyzedThreads(10);++ return `+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Reddit Research Dashboard</title>+ <style>+ :root {+ --bg: #0f172a;+ --card-bg: #1e293b;+ --text: #e2e8f0;+ --text-muted: #94a3b8;+ --accent: #f97316;+ --success: #22c55e;+ --danger: #ef4444;+ --purple: #a855f7;+ }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ background: var(--bg);+ color: var(--text);+ line-height: 1.6;+ padding: 20px;+ }+ .container { max-width: 1400px; margin: 0 auto; }+ header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 30px;+ padding-bottom: 20px;+ border-bottom: 1px solid #334155;+ }+ h1 { font-size: 1.8rem; display: flex; align-items: center; gap: 10px; }+ h1::before { content: 'π'; }+ .stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 20px;+ margin-bottom: 30px;+ }+ .stat-card {+ background: var(--card-bg);+ border-radius: 12px;+ padding: 20px;+ text-align: center;+ }+ .stat-value {+ font-size: 2.5rem;+ font-weight: bold;+ color: var(--accent);+ }+ .stat-label { color: var(--text-muted); font-size: 0.9rem; }+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; }+ .card {+ background: var(--card-bg);+ border-radius: 12px;+ padding: 20px;+ overflow: hidden;+ }+ .card h2 {+ font-size: 1.2rem;+ margin-bottom: 15px;+ padding-bottom: 10px;+ border-bottom: 1px solid #334155;+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .list { list-style: none; }+ .list li {+ padding: 12px 0;+ border-bottom: 1px solid #334155;+ }+ .list li:last-child { border-bottom: none; }+ .list a {+ color: var(--text);+ text-decoration: none;+ }+ .list a:hover { color: var(--accent); }+ .badge {+ display: inline-block;+ padding: 2px 8px;+ border-radius: 4px;+ font-size: 0.75rem;+ font-weight: 600;+ }+ .badge-success { background: var(--success); color: white; }+ .badge-danger { background: var(--danger); color: white; }+ .badge-purple { background: var(--purple); color: white; }+ .badge-muted { background: #475569; color: white; }+ .meta { color: var(--text-muted); font-size: 0.85rem; margin-top: 5px; }+ .score {+ display: inline-block;+ background: var(--accent);+ color: white;+ padding: 2px 8px;+ border-radius: 4px;+ font-weight: bold;+ font-size: 0.85rem;+ }+ .quote {+ background: #334155;+ padding: 10px 15px;+ border-radius: 8px;+ border-left: 3px solid var(--accent);+ font-style: italic;+ margin: 10px 0;+ }+ .empty { color: var(--text-muted); text-align: center; padding: 30px; }+ .refresh-btn {+ background: var(--accent);+ color: white;+ border: none;+ padding: 10px 20px;+ border-radius: 8px;+ cursor: pointer;+ font-weight: 600;+ }+ .refresh-btn:hover { opacity: 0.9; }+ table { width: 100%; border-collapse: collapse; }+ th, td { padding: 10px; text-align: left; border-bottom: 1px solid #334155; }+ th { color: var(--text-muted); font-weight: 500; }+ </style>+</head>+<body>+ <div class="container">+ <header>+ <h1>Reddit Research Dashboard</h1>+ <button class="refresh-btn" onclick="location.reload()">β» Refresh</button>+ </header>++ <div class="stats-grid">+ <div class="stat-card">+ <div class="stat-value">${stats.totalThreads}</div>+ <div class="stat-label">Threads Scanned</div>+ </div>+ <div class="stat-card">+ <div class="stat-value">${stats.analyzedThreads}</div>+ <div class="stat-label">Threads Analyzed</div>+ </div>+ <div class="stat-card">+ <div class="stat-value">${stats.totalInsights}</div>+ <div class="stat-label">Insights Found</div>+ </div>+ <div class="stat-card">+ <div class="stat-value">${stats.topSubreddits.length}</div>+ <div class="stat-label">Subreddits</div>+ </div>+ </div>++ <div class="grid">+ <!-- Pain Points -->+ <div class="card">+ <h2>π΄ Pain Points</h2>+ ${painPoints.length === 0 ? '<div class="empty">No pain points found yet</div>' : `+ <ul class="list">+ ${painPoints.map(p => `+ <li>+ <div>${escapeHtml(p.content)}</div>+ ${p.metadata ? `<div class="meta">Frequency: ${escapeHtml(String((p.metadata as any).frequency || 'N/A'))} | Sentiment: ${escapeHtml(String((p.metadata as any).sentiment || 'N/A'))}</div>` : ''}+ </li>+ `).join('')}+ </ul>+ `}+ </div>++ <!-- Opportunities -->+ <div class="card">+ <h2>π‘ Opportunities</h2>+ ${opportunities.length === 0 ? '<div class="empty">No opportunities found yet</div>' : `+ <ul class="list">+ ${opportunities.map(o => `+ <li>+ <div>+ <span class="badge ${o.confidence === 'high' ? 'badge-success' : o.confidence === 'medium' ? 'badge-purple' : 'badge-muted'}">${escapeHtml(o.confidence || 'unknown')}</span>+ ${escapeHtml(o.content)}+ </div>+ ${o.metadata ? `<div class="meta">Type: ${escapeHtml(String((o.metadata as any).type || 'N/A'))} | Target: ${escapeHtml(String((o.metadata as any).targetAudience || 'N/A'))}</div>` : ''}+ </li>+ `).join('')}+ </ul>+ `}+ </div>++ <!-- Competitors -->+ <div class="card">+ <h2>π’ Competitors Mentioned</h2>+ ${competitors.length === 0 ? '<div class="empty">No competitors found yet</div>' : `+ <ul class="list">+ ${competitors.map(c => `+ <li>+ <div>+ <strong>${escapeHtml(c.content)}</strong>+ <span class="badge ${(c.metadata as any)?.sentiment === 'positive' ? 'badge-success' : (c.metadata as any)?.sentiment === 'negative' ? 'badge-danger' : 'badge-muted'}">${escapeHtml(String((c.metadata as any)?.sentiment || 'neutral'))}</span>+ </div>+ ${c.metadata ? `<div class="meta">${escapeHtml(String((c.metadata as any).context || ''))}</div>` : ''}+ </li>+ `).join('')}+ </ul>+ `}+ </div>++ <!-- Buying Signals -->+ <div class="card">+ <h2>π° Buying Signals</h2>+ ${signals.length === 0 ? '<div class="empty">No buying signals found yet</div>' : `+ <ul class="list">+ ${signals.map(s => `+ <li>+ <div class="quote">"${escapeHtml(s.content.slice(0, 150))}${s.content.length > 150 ? '...' : ''}"</div>+ <div class="meta">+ ${(s.metadata as any)?.author ? `u/${escapeHtml(String((s.metadata as any).author))}` : 'Unknown'}+ ${(s.metadata as any)?.score ? ` β’ ${escapeHtml(String((s.metadata as any).score))} pts` : ''}+ ${(s.metadata as any)?.signalType ? ` β’ ${escapeHtml(String((s.metadata as any).signalType))}` : ''}+ </div>+ </li>+ `).join('')}+ </ul>+ `}+ </div>++ <!-- Top Subreddits -->+ <div class="card">+ <h2>π Top Subreddits</h2>+ <table>+ <thead>+ <tr><th>Subreddit</th><th>Threads</th></tr>+ </thead>+ <tbody>+ ${stats.topSubreddits.map(s => `+ <tr>+ <td>r/${s.subreddit}</td>+ <td>${s.count}</td>+ </tr>+ `).join('')}+ </tbody>+ </table>+ </div>++ <!-- Tracked Sources -->+ <div class="card">+ <h2>π― Tracked Sources</h2>+ ${sources.length === 0 ? '<div class="empty">No sources configured</div>' : `+ <ul class="list">+ ${sources.map(s => `+ <li>+ <div>r/${escapeHtml(s.subreddit)}${s.query ? ` β "${escapeHtml(s.query)}"` : ''}</div>+ ${s.lastScanned ? `<div class="meta">Last scanned: ${escapeHtml(new Date(s.lastScanned).toLocaleString())}</div>` : ''}+ </li>+ `).join('')}+ </ul>+ `}+ </div>++ <!-- Recent Runs -->+ <div class="card">+ <h2>π Recent Runs</h2>+ ${recentRuns.length === 0 ? '<div class="empty">No runs yet</div>' : `+ <table>+ <thead>+ <tr><th>Started</th><th>Status</th><th>Threads</th><th>Insights</th></tr>+ </thead>+ <tbody>+ ${recentRuns.map(r => `+ <tr>+ <td>${escapeHtml(new Date(r.startedAt).toLocaleString())}</td>+ <td><span class="badge ${r.status === 'completed' ? 'badge-success' : r.status === 'running' ? 'badge-purple' : 'badge-danger'}">${escapeHtml(r.status)}</span></td>+ <td>${escapeHtml(String(r.threadsScanned))}</td>+ <td>${escapeHtml(String(r.insightsFound))}</td>+ </tr>+ `).join('')}+ </tbody>+ </table>+ `}+ </div>++ <!-- Unanalyzed Threads -->+ <div class="card">+ <h2>π Queue (Unanalyzed)</h2>+ ${unanalyzed.length === 0 ? '<div class="empty">All threads analyzed!</div>' : `+ <ul class="list">+ ${unanalyzed.map(t => `+ <li>+ <span class="score">${escapeHtml(String(t.goldmineScore))}</span>+ <a href="${escapeHtml(t.url)}" target="_blank">${escapeHtml(t.url.split('/comments/')[1]?.split('/')[1]?.slice(0, 50) || 'View thread')}...</a>+ </li>+ `).join('')}+ </ul>+ `}+ </div>+ </div>+ </div>++ <script>+ // Auto-refresh every 30 seconds+ // setTimeout(() => location.reload(), 30000);+ </script>+</body>+</html>+ `.trim();+}++/**+ * Generate JSON API response+ */+function generateApiResponse(): string {+ const stats = getStats();+ const recentRuns = getRecentRuns(10);+ const sources = getTrackedSources();+ const painPoints = getInsightsByType('pain_point', 50);+ const opportunities = getInsightsByType('opportunity', 50);+ const competitors = getInsightsByType('competitor', 50);+ const signals = getInsightsByType('buying_signal', 50);++ return JSON.stringify({+ stats,+ recentRuns,+ sources,+ insights: {+ painPoints,+ opportunities,+ competitors,+ buyingSignals: signals+ }+ }, null, 2);+}++/**+ * HTTP request handler+ */+function handleRequest(req: IncomingMessage, res: ServerResponse): void {+ const url = req.url || '/';++ // CORS headers+ res.setHeader('Access-Control-Allow-Origin', '*');+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');++ if (req.method === 'OPTIONS') {+ res.writeHead(204);+ res.end();+ return;+ }++ try {+ if (url === '/' || url === '/dashboard') {+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });+ res.end(generateDashboard());+ } else if (url === '/api' || url === '/api/stats') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(generateApiResponse());+ } else if (url === '/api/insights/pain_points') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(getInsightsByType('pain_point', 100)));+ } else if (url === '/api/insights/opportunities') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(getInsightsByType('opportunity', 100)));+ } else if (url === '/api/insights/competitors') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(getInsightsByType('competitor', 100)));+ } else if (url === '/api/insights/buying_signals') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(getInsightsByType('buying_signal', 100)));+ } else {+ res.writeHead(404, { 'Content-Type': 'text/plain' });+ res.end('Not Found');+ }+ } catch (error) {+ console.error('Dashboard error:', error);+ res.writeHead(500, { 'Content-Type': 'text/plain' });+ res.end(`Server Error: ${error}`);+ }+}++/**+ * Start dashboard server+ */+export function startDashboard(port = 3456, dbPath?: string): void {+ // Initialize database+ initDatabase(dbPath);++ const server = createServer(handleRequest);++ server.listen(port, () => {+ console.log(`\nπ― Reddit Research Dashboard`);+ console.log(` http://localhost:${port}`);+ console.log(` http://localhost:${port}/api (JSON API)`);+ console.log(`\nPress Ctrl+C to stop\n`);+ });+}++// CLI entry point+if (process.argv[1]?.includes('dashboard')) {+ const port = parseInt(process.argv[2] || '3456', 10);+ startDashboard(port);+}diff --git a/agents/reddit-research/src/db/database.ts b/agents/reddit-research/src/db/database.tsnew file mode 100644index 0000000..01646a5--- /dev/null+++ b/agents/reddit-research/src/db/database.ts@@ -0,0 +1,361 @@+/**+ * Database operations for Reddit Research Agent+ */++import Database from 'better-sqlite3';+import { randomUUID } from 'crypto';+import { SCHEMA } from './schema.js';+import type { GoldmineScore } from '../types.js';++let db: Database.Database | null = null;++/**+ * Initialize database connection+ */+export function initDatabase(dbPath = './reddit-research.db'): Database.Database {+ if (db) return db;++ db = new Database(dbPath);+ db.pragma('journal_mode = WAL');+ db.exec(SCHEMA);++ return db;+}++/**+ * Get database instance+ */+export function getDb(): Database.Database {+ if (!db) {+ throw new Error('Database not initialized. Call initDatabase() first.');+ }+ return db;+}++/**+ * Close database connection+ */+export function closeDatabase(): void {+ if (db) {+ db.close();+ db = null;+ }+}++// ==================== Thread Operations ====================++/**+ * Save scanned threads to database+ */+export function saveThreads(threads: GoldmineScore[]): number {+ const database = getDb();+ const stmt = database.prepare(`+ INSERT OR REPLACE INTO threads+ (id, url, subreddit, title, score, num_comments, upvote_ratio, goldmine_score, scanned_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ `);++ let count = 0;+ const now = new Date().toISOString();++ for (const thread of threads) {+ const id = thread.url.split('/comments/')[1]?.split('/')[0] || randomUUID();+ stmt.run(+ id,+ thread.url,+ thread.subreddit,+ thread.title,+ thread.score,+ thread.numComments,+ thread.upvoteRatio,+ thread.goldmineScore,+ now+ );+ count++;+ }++ return count;+}++/**+ * Get unanalyzed threads sorted by goldmine score+ */+export function getUnanalyzedThreads(limit = 10): Array<{ id: string; url: string; goldmineScore: number }> {+ const database = getDb();+ return database.prepare(`+ SELECT id, url, goldmine_score as goldmineScore+ FROM threads+ WHERE analyzed = 0+ ORDER BY goldmine_score DESC+ LIMIT ?+ `).all(limit) as Array<{ id: string; url: string; goldmineScore: number }>;+}++/**+ * Mark thread as analyzed+ */+export function markThreadAnalyzed(threadId: string): void {+ const database = getDb();+ database.prepare('UPDATE threads SET analyzed = 1 WHERE id = ?').run(threadId);+}++/**+ * Get thread by ID+ */+export function getThread(threadId: string): GoldmineScore | null {+ const database = getDb();+ const row = database.prepare('SELECT * FROM threads WHERE id = ?').get(threadId) as any;+ if (!row) return null;++ return {+ url: row.url,+ title: row.title,+ score: row.score,+ numComments: row.num_comments,+ upvoteRatio: row.upvote_ratio,+ goldmineScore: row.goldmine_score,+ subreddit: row.subreddit,+ };+}++// ==================== Insight Operations ====================++/**+ * Save market insights+ */+export function saveInsight(+ threadId: string,+ type: string,+ content: string,+ metadata?: Record<string, unknown>,+ confidence?: string+): string {+ const database = getDb();+ const id = randomUUID();++ database.prepare(`+ INSERT INTO insights (id, thread_id, type, content, metadata, confidence, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ `).run(+ id,+ threadId,+ type,+ content,+ metadata ? JSON.stringify(metadata) : null,+ confidence || null,+ new Date().toISOString()+ );++ return id;+}++/**+ * Get insights by type+ */+export function getInsightsByType(type: string, limit = 50): Array<{+ id: string;+ threadId: string;+ content: string;+ metadata: Record<string, unknown> | null;+ confidence: string | null;+ createdAt: string;+}> {+ const database = getDb();+ const rows = database.prepare(`+ SELECT id, thread_id as threadId, content, metadata, confidence, created_at as createdAt+ FROM insights+ WHERE type = ?+ ORDER BY created_at DESC+ LIMIT ?+ `).all(type, limit) as any[];++ return rows.map(row => ({+ ...row,+ metadata: row.metadata ? JSON.parse(row.metadata) : null,+ }));+}++/**+ * Get all insights for a thread+ */+export function getThreadInsights(threadId: string): Array<{+ type: string;+ content: string;+ metadata: Record<string, unknown> | null;+}> {+ const database = getDb();+ const rows = database.prepare(`+ SELECT type, content, metadata+ FROM insights+ WHERE thread_id = ?+ ORDER BY type, created_at+ `).all(threadId) as any[];++ return rows.map(row => ({+ type: row.type,+ content: row.content,+ metadata: row.metadata ? JSON.parse(row.metadata) : null,+ }));+}++// ==================== Agent Run Operations ====================++/**+ * Start a new agent run+ */+export function startAgentRun(): number {+ const database = getDb();+ const result = database.prepare(`+ INSERT INTO agent_runs (started_at, status)+ VALUES (?, 'running')+ `).run(new Date().toISOString());++ return result.lastInsertRowid as number;+}++/**+ * Complete an agent run+ */+export function completeAgentRun(+ runId: number,+ stats: { threadsScanned: number; insightsFound: number; costUsd: number }+): void {+ const database = getDb();+ database.prepare(`+ UPDATE agent_runs+ SET completed_at = ?, status = 'completed',+ threads_scanned = ?, insights_found = ?, cost_usd = ?+ WHERE id = ?+ `).run(+ new Date().toISOString(),+ stats.threadsScanned,+ stats.insightsFound,+ stats.costUsd,+ runId+ );+}++/**+ * Fail an agent run+ */+export function failAgentRun(runId: number, error: string): void {+ const database = getDb();+ database.prepare(`+ UPDATE agent_runs+ SET completed_at = ?, status = 'failed', error_message = ?+ WHERE id = ?+ `).run(new Date().toISOString(), error, runId);+}++/**+ * Get recent agent runs+ */+export function getRecentRuns(limit = 10): Array<{+ id: number;+ startedAt: string;+ completedAt: string | null;+ status: string;+ threadsScanned: number;+ insightsFound: number;+ costUsd: number;+}> {+ const database = getDb();+ return database.prepare(`+ SELECT id, started_at as startedAt, completed_at as completedAt,+ status, threads_scanned as threadsScanned,+ insights_found as insightsFound, cost_usd as costUsd+ FROM agent_runs+ ORDER BY id DESC+ LIMIT ?+ `).all(limit) as any[];+}++// ==================== Tracked Sources ====================++/**+ * Add a subreddit to track+ */+export function addTrackedSource(subreddit: string, query?: string): void {+ const database = getDb();+ database.prepare(`+ INSERT OR IGNORE INTO tracked_sources (subreddit, query, created_at)+ VALUES (?, ?, ?)+ `).run(subreddit, query || null, new Date().toISOString());+}++/**+ * Get all tracked sources+ */+export function getTrackedSources(): Array<{+ id: number;+ subreddit: string;+ query: string | null;+ enabled: boolean;+ lastScanned: string | null;+}> {+ const database = getDb();+ return database.prepare(`+ SELECT id, subreddit, query, enabled, last_scanned as lastScanned+ FROM tracked_sources+ WHERE enabled = 1+ `).all() as any[];+}++/**+ * Update last scanned time for a source+ */+export function updateSourceScanned(subreddit: string, query?: string): void {+ const database = getDb();+ if (query) {+ database.prepare(`+ UPDATE tracked_sources SET last_scanned = ? WHERE subreddit = ? AND query = ?+ `).run(new Date().toISOString(), subreddit, query);+ } else {+ database.prepare(`+ UPDATE tracked_sources SET last_scanned = ? WHERE subreddit = ? AND query IS NULL+ `).run(new Date().toISOString(), subreddit);+ }+}++// ==================== Stats ====================++/**+ * Get database statistics+ */+export function getStats(): {+ totalThreads: number;+ analyzedThreads: number;+ totalInsights: number;+ insightsByType: Record<string, number>;+ topSubreddits: Array<{ subreddit: string; count: number }>;+} {+ const database = getDb();++ const totalThreads = (database.prepare('SELECT COUNT(*) as count FROM threads').get() as any).count;+ const analyzedThreads = (database.prepare('SELECT COUNT(*) as count FROM threads WHERE analyzed = 1').get() as any).count;+ const totalInsights = (database.prepare('SELECT COUNT(*) as count FROM insights').get() as any).count;++ const insightsByTypeRows = database.prepare(`+ SELECT type, COUNT(*) as count FROM insights GROUP BY type+ `).all() as any[];+ const insightsByType: Record<string, number> = {};+ for (const row of insightsByTypeRows) {+ insightsByType[row.type] = row.count;+ }++ const topSubreddits = database.prepare(`+ SELECT subreddit, COUNT(*) as count+ FROM threads+ GROUP BY subreddit+ ORDER BY count DESC+ LIMIT 10+ `).all() as any[];++ return {+ totalThreads,+ analyzedThreads,+ totalInsights,+ insightsByType,+ topSubreddits,+ };+}diff --git a/agents/reddit-research/src/db/index.ts b/agents/reddit-research/src/db/index.tsnew file mode 100644index 0000000..0b9ada6--- /dev/null+++ b/agents/reddit-research/src/db/index.ts@@ -0,0 +1,2 @@+export * from './database.js';+export * from './schema.js';diff --git a/agents/reddit-research/src/db/schema.ts b/agents/reddit-research/src/db/schema.tsnew file mode 100644index 0000000..7e53ef3--- /dev/null+++ b/agents/reddit-research/src/db/schema.ts@@ -0,0 +1,64 @@+/**+ * SQLite Database Schema+ */++export const SCHEMA = `+-- Scanned threads+CREATE TABLE IF NOT EXISTS threads (+ id TEXT PRIMARY KEY,+ url TEXT UNIQUE NOT NULL,+ subreddit TEXT NOT NULL,+ title TEXT NOT NULL,+ score INTEGER DEFAULT 0,+ num_comments INTEGER DEFAULT 0,+ upvote_ratio REAL DEFAULT 0,+ goldmine_score REAL DEFAULT 0,+ selftext TEXT,+ author TEXT,+ created_utc INTEGER,+ scanned_at TEXT NOT NULL,+ analyzed INTEGER DEFAULT 0+);++-- Market insights extracted from threads+CREATE TABLE IF NOT EXISTS insights (+ id TEXT PRIMARY KEY,+ thread_id TEXT NOT NULL,+ type TEXT NOT NULL, -- 'pain_point', 'opportunity', 'competitor', 'buying_signal', 'quote'+ content TEXT NOT NULL,+ metadata TEXT, -- JSON for additional fields+ confidence TEXT, -- 'high', 'medium', 'low'+ created_at TEXT NOT NULL,+ FOREIGN KEY (thread_id) REFERENCES threads(id)+);++-- Agent run history+CREATE TABLE IF NOT EXISTS agent_runs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ started_at TEXT NOT NULL,+ completed_at TEXT,+ status TEXT DEFAULT 'running', -- 'running', 'completed', 'failed'+ threads_scanned INTEGER DEFAULT 0,+ insights_found INTEGER DEFAULT 0,+ cost_usd REAL DEFAULT 0,+ error_message TEXT+);++-- Tracked subreddits and queries+CREATE TABLE IF NOT EXISTS tracked_sources (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ subreddit TEXT NOT NULL,+ query TEXT,+ enabled INTEGER DEFAULT 1,+ last_scanned TEXT,+ created_at TEXT NOT NULL,+ UNIQUE(subreddit, query)+);++-- Indexes for performance+CREATE INDEX IF NOT EXISTS idx_threads_subreddit ON threads(subreddit);+CREATE INDEX IF NOT EXISTS idx_threads_goldmine ON threads(goldmine_score DESC);+CREATE INDEX IF NOT EXISTS idx_threads_analyzed ON threads(analyzed);+CREATE INDEX IF NOT EXISTS idx_insights_type ON insights(type);+CREATE INDEX IF NOT EXISTS idx_insights_thread ON insights(thread_id);+`;diff --git a/agents/reddit-research/src/index.ts b/agents/reddit-research/src/index.tsnew file mode 100644index 0000000..a419831--- /dev/null+++ b/agents/reddit-research/src/index.ts@@ -0,0 +1,57 @@+/**+ * Reddit Research Agent+ * Extract market research gold from Reddit threads+ */++// Core exports+export * from './types.js';+export * from './reddit/index.js';+export * from './db/index.js';+export * from './agent/analyzer.js';+export * from './agent/runner.js';++// Production features+export * from './alerts/index.js';+export * from './sync/index.js';+export * from './dashboard/index.js';+export * from './agent/multiAgent.js';+export * from './utils/rateLimiter.js';++// Quick usage example+import { findGoldmineThreads, fetchThread } from './reddit/index.js';+import { analyzeThread } from './agent/analyzer.js';++export async function quickResearch(subreddit: string, query?: string) {+ console.log(`π Researching r/${subreddit}${query ? ` for "${query}"` : ''}...\n`);++ // Find goldmine threads+ const threads = await findGoldmineThreads(subreddit, query ? [query] : undefined);++ console.log(`Found ${threads.length} goldmine threads:\n`);++ // Show top 5+ for (const thread of threads.slice(0, 5)) {+ console.log(`[${thread.goldmineScore}] ${thread.title.slice(0, 60)}...`);+ console.log(` π ${thread.score} pts | π¬ ${thread.numComments} comments`);+ console.log(` π ${thread.url}\n`);+ }++ // Analyze top thread+ if (threads.length > 0) {+ console.log('\nπ Analyzing top thread...\n');+ const topThread = await fetchThread(threads[0].url);+ const insights = await analyzeThread(topThread);++ console.log('Summary:', insights.summary);+ console.log('\nPain Points:');+ for (const pp of insights.painPoints) {+ console.log(` - ${pp.description}`);+ }+ console.log('\nOpportunities:');+ for (const opp of insights.opportunities) {+ console.log(` - [${opp.confidence}] ${opp.description}`);+ }+ }++ return threads;+}diff --git a/agents/reddit-research/src/reddit/fetcher.ts b/agents/reddit-research/src/reddit/fetcher.tsnew file mode 100644index 0000000..deba474--- /dev/null+++ b/agents/reddit-research/src/reddit/fetcher.ts@@ -0,0 +1,228 @@+/**+ * Reddit JSON API Fetcher+ * Uses the hidden /.json endpoint to fetch thread data+ */++import { execFileNoThrow } from '../utils/execFileNoThrow.js';+import type { RedditPost, RedditComment, ThreadData, ThreadMetrics, GoldmineScore } from '../types.js';++const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';++/**+ * Fetch JSON from Reddit using curl (bypasses urllib fingerprinting)+ */+async function fetchRedditJson(url: string): Promise<unknown> {+ // Normalize URL+ url = url.replace('reddit.com', 'www.reddit.com');+ if (url.includes('www.www.')) {+ url = url.replace('www.www.', 'www.');+ }+ if (!url.endsWith('.json')) {+ url = url.replace(/\/?$/, '.json');+ }++ const result = await execFileNoThrow('curl', ['-s', '-A', USER_AGENT, url], {+ maxBuffer: 10 * 1024 * 1024, // 10MB buffer for large threads+ });++ if (result.status === 'error' || !result.stdout) {+ throw new Error(`Failed to fetch Reddit: ${result.stderr}`);+ }++ return JSON.parse(result.stdout);+}++/**+ * Extract comments recursively from Reddit's nested structure+ */+function extractComments(children: any[], depth = 0): RedditComment[] {+ const results: RedditComment[] = [];++ for (const child of children) {+ if (child.kind === 't1') { // t1 = comment+ const data = child.data;+ const comment: RedditComment = {+ id: data.id,+ body: data.body || '',+ score: data.score || 0,+ author: data.author || '[deleted]',+ depth,+ createdUtc: data.created_utc,+ repliesCount: 0,+ };++ // Extract nested replies+ let replies: RedditComment[] = [];+ if (data.replies && typeof data.replies === 'object') {+ const replyChildren = data.replies?.data?.children || [];+ replies = extractComments(replyChildren, depth + 1);+ comment.repliesCount = replies.length;+ }++ results.push(comment);+ results.push(...replies);+ }+ }++ return results;+}++/**+ * Fetch and structure a Reddit thread+ */+export async function fetchThread(url: string): Promise<ThreadData> {+ const data = await fetchRedditJson(url) as any[];++ // Extract post+ const postData = data[0].data.children[0].data;+ const post: RedditPost = {+ id: postData.id,+ title: postData.title || '',+ selftext: postData.selftext || '',+ score: postData.score || 0,+ upvoteRatio: postData.upvote_ratio || 0,+ numComments: postData.num_comments || 0,+ author: postData.author || '[deleted]',+ subreddit: postData.subreddit || '',+ permalink: postData.permalink || '',+ url: `https://reddit.com${postData.permalink}`,+ createdUtc: postData.created_utc,+ flair: postData.link_flair_text,+ };++ // Extract all comments+ const allComments = extractComments(data[1].data.children);++ // Sort by score for top comments+ const topComments = [...allComments]+ .sort((a, b) => b.score - a.score)+ .slice(0, 30);++ // Calculate metrics+ const totalCommentScore = allComments.reduce((sum, c) => sum + c.score, 0);+ const metrics: ThreadMetrics = {+ totalComments: allComments.length,+ totalCommentScore,+ avgCommentScore: allComments.length > 0 ? Math.round((totalCommentScore / allComments.length) * 100) / 100 : 0,+ maxDepth: Math.max(...allComments.map(c => c.depth), 0),+ uniqueAuthors: new Set(allComments.map(c => c.author)).size,+ };++ return {+ extractedAt: new Date().toISOString(),+ post,+ metrics,+ topComments,+ allComments,+ };+}++/**+ * Search a subreddit for threads+ */+export async function searchSubreddit(+ subreddit: string,+ query?: string,+ options: { sort?: string; time?: string; limit?: number } = {}+): Promise<GoldmineScore[]> {+ const { sort = 'top', time = 'year', limit = 25 } = options;++ let url: string;+ if (query) {+ const encodedQuery = encodeURIComponent(query);+ url = `https://www.reddit.com/r/${subreddit}/search.json?q=${encodedQuery}&restrict_sr=1&sort=${sort}&t=${time}&limit=${limit}`;+ } else {+ url = `https://www.reddit.com/r/${subreddit}/${sort}.json?t=${time}&limit=${limit}`;+ }++ const data = await fetchRedditJson(url) as any;+ const threads: GoldmineScore[] = [];++ for (const child of data.data?.children || []) {+ const p = child.data;+ threads.push({+ url: `https://reddit.com${p.permalink}`,+ title: p.title || '',+ score: p.score || 0,+ numComments: p.num_comments || 0,+ upvoteRatio: p.upvote_ratio || 0,+ goldmineScore: calculateGoldmineScore(p),+ subreddit: p.subreddit || subreddit,+ });+ }++ return threads;+}++/**+ * Calculate how valuable a thread is for market research+ */+function calculateGoldmineScore(post: any): number {+ let score = 0;++ // High comment count = lots of discussion+ score += Math.min((post.num_comments || 0) / 10, 20);++ // Good upvote ratio = quality content+ score += (post.upvote_ratio || 0) * 10;++ // Post score indicates visibility+ score += Math.min((post.score || 0) / 50, 10);++ // Bonus for goldmine keywords in title+ const titleLower = (post.title || '').toLowerCase();+ const goldmineKeywords = [+ 'wish', 'hate', 'love', 'best', 'worst', 'looking for',+ 'recommend', 'help', 'advice', 'alternative', 'switched',+ 'paying', 'worth it', 'frustrat', 'problem', 'solution'+ ];++ for (const kw of goldmineKeywords) {+ if (titleLower.includes(kw)) {+ score += 3;+ }+ }++ return Math.round(score * 100) / 100;+}++/**+ * Find goldmine threads across multiple queries+ */+export async function findGoldmineThreads(+ subreddit: string,+ queries: string[] = []+): Promise<GoldmineScore[]> {+ const defaultQueries = [+ 'wish existed',+ 'hate about',+ 'frustrating',+ 'looking for',+ 'recommend',+ 'alternative to',+ 'switched from',+ 'paying for',+ 'game changer',+ ];++ const searchQueries = queries.length > 0 ? queries : defaultQueries;+ const allThreads: GoldmineScore[] = [];+ const seenUrls = new Set<string>();++ for (const query of searchQueries) {+ try {+ const threads = await searchSubreddit(subreddit, query, { limit: 10 });+ for (const thread of threads) {+ if (!seenUrls.has(thread.url)) {+ seenUrls.add(thread.url);+ allThreads.push(thread);+ }+ }+ } catch (error) {+ console.error(`Failed to search "${query}":`, error);+ }+ }++ // Sort by goldmine score+ return allThreads.sort((a, b) => b.goldmineScore - a.goldmineScore);+}diff --git a/agents/reddit-research/src/reddit/index.ts b/agents/reddit-research/src/reddit/index.tsnew file mode 100644index 0000000..1c0fe00--- /dev/null+++ b/agents/reddit-research/src/reddit/index.ts@@ -0,0 +1 @@+export * from './fetcher.js';diff --git a/agents/reddit-research/src/sync/index.ts b/agents/reddit-research/src/sync/index.tsnew file mode 100644index 0000000..0c472a9--- /dev/null+++ b/agents/reddit-research/src/sync/index.ts@@ -0,0 +1 @@+export * from './notion.js';diff --git a/agents/reddit-research/src/sync/notion.ts b/agents/reddit-research/src/sync/notion.tsnew file mode 100644index 0000000..efeeebc--- /dev/null+++ b/agents/reddit-research/src/sync/notion.ts@@ -0,0 +1,452 @@+/**+ * Notion Sync Integration+ * Automatically pushes insights to Notion database+ */++import { execFileNoThrow } from '../utils/execFileNoThrow.js';+import type { GoldmineScore, MarketInsight, ThreadData } from '../types.js';++export interface NotionConfig {+ apiKey: string;+ databaseId?: string;+ parentPageId?: string;+}++interface NotionPage {+ id: string;+ url: string;+}++/**+ * Make Notion API request+ */+async function notionRequest(+ apiKey: string,+ endpoint: string,+ method: string,+ body?: Record<string, unknown>+): Promise<{ success: boolean; data?: any; error?: string }> {+ const args = [+ '-s',+ '-X', method,+ `https://api.notion.com/v1${endpoint}`,+ '-H', `Authorization: Bearer ${apiKey}`,+ '-H', 'Content-Type: application/json',+ '-H', 'Notion-Version: 2022-06-28'+ ];++ if (body) {+ args.push('-d', JSON.stringify(body));+ }++ const result = await execFileNoThrow('curl', args);++ if (result.status === 'error') {+ return { success: false, error: result.stderr };+ }++ try {+ const data = JSON.parse(result.stdout);+ if (data.object === 'error') {+ return { success: false, error: data.message };+ }+ return { success: true, data };+ } catch {+ return { success: false, error: 'Invalid JSON response' };+ }+}++/**+ * Create a Notion page with thread data+ */+async function createThreadPage(+ apiKey: string,+ parentId: string,+ thread: GoldmineScore,+ insights?: MarketInsight+): Promise<NotionPage | null> {+ // Build rich text content+ const content: any[] = [+ {+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'Thread Info' } }]+ }+ },+ {+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [{ type: 'text', text: { content: `Subreddit: r/${thread.subreddit}` } }]+ }+ },+ {+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [{ type: 'text', text: { content: `Score: ${thread.score} pts` } }]+ }+ },+ {+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [{ type: 'text', text: { content: `Comments: ${thread.numComments}` } }]+ }+ },+ {+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [{ type: 'text', text: { content: `Goldmine Score: ${thread.goldmineScore}` } }]+ }+ },+ {+ object: 'block',+ type: 'bookmark',+ bookmark: { url: thread.url }+ }+ ];++ // Add insights if available+ if (insights) {+ // Summary+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'Summary' } }]+ }+ });+ content.push({+ object: 'block',+ type: 'callout',+ callout: {+ icon: { emoji: 'π' },+ rich_text: [{ type: 'text', text: { content: insights.summary } }]+ }+ });++ // Pain Points+ if (insights.painPoints.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'π΄ Pain Points' } }]+ }+ });+ for (const pp of insights.painPoints) {+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [+ { type: 'text', text: { content: pp.description } },+ { type: 'text', text: { content: ` (${pp.sentiment}, freq: ${pp.frequency})` }, annotations: { color: 'gray' } }+ ]+ }+ });+ }+ }++ // Opportunities+ if (insights.opportunities.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'π‘ Opportunities' } }]+ }+ });+ for (const opp of insights.opportunities) {+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [+ { type: 'text', text: { content: `[${opp.confidence}] ` }, annotations: { bold: true } },+ { type: 'text', text: { content: opp.description } },+ { type: 'text', text: { content: ` β ${opp.targetAudience}` }, annotations: { color: 'gray' } }+ ]+ }+ });+ }+ }++ // Competitor Mentions+ if (insights.competitorMentions.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'π’ Competitors' } }]+ }+ });+ for (const comp of insights.competitorMentions) {+ const emoji = comp.sentiment === 'positive' ? 'π' : comp.sentiment === 'negative' ? 'π' : 'β';+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [+ { type: 'text', text: { content: `${emoji} ${comp.name}` }, annotations: { bold: true } },+ { type: 'text', text: { content: ` - ${comp.context}` } }+ ]+ }+ });+ }+ }++ // Buying Signals+ if (insights.buyingSignals.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'π° Buying Signals' } }]+ }+ });+ for (const signal of insights.buyingSignals) {+ content.push({+ object: 'block',+ type: 'quote',+ quote: {+ rich_text: [+ { type: 'text', text: { content: `"${signal.quote.slice(0, 200)}${signal.quote.length > 200 ? '...' : ''}"` } },+ { type: 'text', text: { content: ` β u/${signal.author}` }, annotations: { italic: true, color: 'gray' } }+ ]+ }+ });+ }+ }++ // Key Quotes+ if (insights.keyQuotes.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: {+ rich_text: [{ type: 'text', text: { content: 'π¬ Key Quotes' } }]+ }+ });+ for (const quote of insights.keyQuotes) {+ content.push({+ object: 'block',+ type: 'quote',+ quote: {+ rich_text: [+ { type: 'text', text: { content: `"${quote.text.slice(0, 300)}${quote.text.length > 300 ? '...' : ''}"` } },+ { type: 'text', text: { content: ` β u/${quote.author} (${quote.score} pts)` }, annotations: { italic: true, color: 'gray' } }+ ]+ }+ });+ }+ }+ }++ const response = await notionRequest(apiKey, '/pages', 'POST', {+ parent: { page_id: parentId },+ icon: { emoji: 'π' },+ properties: {+ title: {+ title: [{ text: { content: `${thread.title.slice(0, 100)}` } }]+ }+ },+ children: content.slice(0, 100) // Notion limit+ });++ if (!response.success) {+ console.error('Failed to create Notion page:', response.error);+ return null;+ }++ return {+ id: response.data.id,+ url: response.data.url+ };+}++/**+ * Notion Sync Manager+ */+export class NotionSync {+ private config: NotionConfig;+ private verbose: boolean;++ constructor(config: NotionConfig, options: { verbose?: boolean } = {}) {+ this.config = config;+ this.verbose = options.verbose ?? false;+ }++ /**+ * Check if Notion is properly configured+ */+ isConfigured(): boolean {+ return !!(this.config.apiKey && (this.config.parentPageId || this.config.databaseId));+ }++ /**+ * Sync a thread to Notion+ */+ async syncThread(thread: GoldmineScore, insights?: MarketInsight): Promise<NotionPage | null> {+ const parentId = this.config.parentPageId || this.config.databaseId;+ if (!parentId) {+ if (this.verbose) {+ console.error('No Notion parent page or database configured');+ }+ return null;+ }++ return createThreadPage(this.config.apiKey, parentId, thread, insights);+ }++ /**+ * Sync multiple threads (simple format - just threads)+ */+ async syncThreads(threads: GoldmineScore[]): Promise<NotionPage[]> {+ const pages: NotionPage[] = [];++ for (const thread of threads) {+ const page = await this.syncThread(thread);+ if (page) {+ pages.push(page);+ if (this.verbose) {+ console.log(`Synced to Notion: ${thread.title.slice(0, 40)}...`);+ }+ }+ // Rate limit: 3 requests per second+ await new Promise(resolve => setTimeout(resolve, 350));+ }++ return pages;+ }++ /**+ * Sync multiple threads with insights+ */+ async syncThreadsWithInsights(threads: Array<{ thread: GoldmineScore; insights?: MarketInsight }>): Promise<NotionPage[]> {+ const pages: NotionPage[] = [];++ for (const { thread, insights } of threads) {+ const page = await this.syncThread(thread, insights);+ if (page) {+ pages.push(page);+ }+ // Rate limit: 3 requests per second+ await new Promise(resolve => setTimeout(resolve, 350));+ }++ return pages;+ }++ /**+ * Create a daily digest page+ */+ async createDigest(date: string, stats: {+ threadsScanned: number;+ insightsFound: number;+ topThreads: GoldmineScore[];+ topPainPoints: string[];+ topOpportunities: string[];+ }): Promise<NotionPage | null> {+ const parentId = this.config.parentPageId || this.config.databaseId;+ if (!parentId) {+ return null;+ }++ const content: any[] = [+ {+ object: 'block',+ type: 'callout',+ callout: {+ icon: { emoji: 'π' },+ rich_text: [{+ type: 'text',+ text: { content: `Scanned ${stats.threadsScanned} threads, found ${stats.insightsFound} insights` }+ }]+ }+ },+ {+ object: 'block',+ type: 'heading_2',+ heading_2: { rich_text: [{ type: 'text', text: { content: 'Top Threads' } }] }+ }+ ];++ for (const thread of stats.topThreads.slice(0, 5)) {+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: {+ rich_text: [+ { type: 'text', text: { content: `[${thread.goldmineScore}] ` }, annotations: { bold: true } },+ { type: 'text', text: { content: thread.title.slice(0, 60), link: { url: thread.url } } }+ ]+ }+ });+ }++ if (stats.topPainPoints.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: { rich_text: [{ type: 'text', text: { content: 'π΄ Top Pain Points' } }] }+ });+ for (const pp of stats.topPainPoints.slice(0, 5)) {+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: { rich_text: [{ type: 'text', text: { content: pp } }] }+ });+ }+ }++ if (stats.topOpportunities.length > 0) {+ content.push({+ object: 'block',+ type: 'heading_2',+ heading_2: { rich_text: [{ type: 'text', text: { content: 'π‘ Top Opportunities' } }] }+ });+ for (const opp of stats.topOpportunities.slice(0, 5)) {+ content.push({+ object: 'block',+ type: 'bulleted_list_item',+ bulleted_list_item: { rich_text: [{ type: 'text', text: { content: opp } }] }+ });+ }+ }++ const response = await notionRequest(this.config.apiKey, '/pages', 'POST', {+ parent: { page_id: parentId },+ icon: { emoji: 'π ' },+ properties: {+ title: { title: [{ text: { content: `Research Digest - ${date}` } }] }+ },+ children: content+ });++ if (!response.success) {+ return null;+ }++ return { id: response.data.id, url: response.data.url };+ }+}++/**+ * Create Notion sync from environment+ */+export function createNotionSync(options: { verbose?: boolean } = {}): NotionSync | null {+ const apiKey = process.env.NOTION_API_KEY;+ if (!apiKey) {+ return null;+ }++ return new NotionSync({+ apiKey,+ parentPageId: process.env.NOTION_PARENT_PAGE_ID,+ databaseId: process.env.NOTION_DATABASE_ID+ }, options);+}diff --git a/agents/reddit-research/src/types.ts b/agents/reddit-research/src/types.tsnew file mode 100644index 0000000..2fb177e--- /dev/null+++ b/agents/reddit-research/src/types.ts@@ -0,0 +1,117 @@+/**+ * Core types for Reddit Research Agent+ */++export interface RedditPost {+ id: string;+ title: string;+ selftext: string;+ score: number;+ upvoteRatio: number;+ numComments: number;+ author: string;+ subreddit: string;+ permalink: string;+ url: string;+ createdUtc: number;+ flair?: string;+}++export interface RedditComment {+ id: string;+ body: string;+ score: number;+ author: string;+ depth: number;+ createdUtc: number;+ repliesCount: number;+}++export interface ThreadData {+ extractedAt: string;+ post: RedditPost;+ metrics: ThreadMetrics;+ topComments: RedditComment[];+ allComments: RedditComment[];+}++export interface ThreadMetrics {+ totalComments: number;+ totalCommentScore: number;+ avgCommentScore: number;+ maxDepth: number;+ uniqueAuthors: number;+}++export interface GoldmineScore {+ url: string;+ title: string;+ score: number;+ numComments: number;+ upvoteRatio: number;+ goldmineScore: number;+ subreddit: string;+}++export interface MarketInsight {+ id: string;+ threadUrl: string;+ subreddit: string;+ extractedAt: string;+ painPoints: PainPoint[];+ opportunities: Opportunity[];+ competitorMentions: CompetitorMention[];+ buyingSignals: BuyingSignal[];+ keyQuotes: KeyQuote[];+ summary: string;+}++export interface PainPoint {+ description: string;+ frequency: number;+ sentiment: 'frustrated' | 'annoyed' | 'desperate' | 'neutral';+ quotes: string[];+}++export interface Opportunity {+ description: string;+ type: 'product' | 'feature' | 'service' | 'content';+ confidence: 'high' | 'medium' | 'low';+ targetAudience: string;+}++export interface CompetitorMention {+ name: string;+ sentiment: 'positive' | 'negative' | 'neutral';+ context: string;+ frequency: number;+}++export interface BuyingSignal {+ quote: string;+ author: string;+ signalType: 'looking' | 'considering' | 'ready' | 'switched';+ score: number;+}++export interface KeyQuote {+ text: string;+ author: string;+ score: number;+ insightType: string;+}++export interface ScanConfig {+ subreddits: string[];+ queries: string[];+ schedule: string; // cron expression+ maxThreadsPerScan: number;+ minGoldmineScore: number;+}++export interface AgentState {+ lastScan: string;+ threadsAnalyzed: number;+ insightsFound: number;+ totalCost: number;+}diff --git a/agents/reddit-research/src/utils/execFileNoThrow.ts b/agents/reddit-research/src/utils/execFileNoThrow.tsnew file mode 100644index 0000000..e5ffa68--- /dev/null+++ b/agents/reddit-research/src/utils/execFileNoThrow.ts@@ -0,0 +1,45 @@+/**+ * Safe command execution utility+ * Uses execFile instead of exec to prevent shell injection+ */++import { execFile } from 'child_process';+import { promisify } from 'util';++const execFileAsync = promisify(execFile);++export interface ExecResult {+ stdout: string;+ stderr: string;+ status: 'success' | 'error';+ code?: number;+}++/**+ * Execute a command safely without shell interpolation+ */+export async function execFileNoThrow(+ command: string,+ args: string[],+ options: { maxBuffer?: number; timeout?: number } = {}+): Promise<ExecResult> {+ try {+ const { stdout, stderr } = await execFileAsync(command, args, {+ maxBuffer: options.maxBuffer || 10 * 1024 * 1024, // 10MB+ timeout: options.timeout || 30000, // 30s+ });++ return {+ stdout,+ stderr,+ status: 'success',+ };+ } catch (error: any) {+ return {+ stdout: error.stdout || '',+ stderr: error.stderr || error.message,+ status: 'error',+ code: error.code,+ };+ }+}diff --git a/agents/reddit-research/src/utils/index.ts b/agents/reddit-research/src/utils/index.tsnew file mode 100644index 0000000..b87e54d--- /dev/null+++ b/agents/reddit-research/src/utils/index.ts@@ -0,0 +1,2 @@+export * from './execFileNoThrow.js';+export * from './rateLimiter.js';diff --git a/agents/reddit-research/src/utils/rateLimiter.ts b/agents/reddit-research/src/utils/rateLimiter.tsnew file mode 100644index 0000000..55109ce--- /dev/null+++ b/agents/reddit-research/src/utils/rateLimiter.ts@@ -0,0 +1,230 @@+/**+ * Rate Limiter+ * Prevents hitting Reddit's rate limits (60 requests per minute)+ */++export interface RateLimiterConfig {+ maxRequests: number;+ windowMs: number;+ retryAfterMs?: number;+}++/**+ * Token bucket rate limiter+ */+export class RateLimiter {+ private tokens: number;+ private maxTokens: number;+ private refillRate: number; // tokens per ms+ private lastRefill: number;+ private retryAfterMs: number;++ constructor(config: RateLimiterConfig) {+ this.maxTokens = config.maxRequests;+ this.tokens = config.maxRequests;+ this.refillRate = config.maxRequests / config.windowMs;+ this.lastRefill = Date.now();+ this.retryAfterMs = config.retryAfterMs || 1000;+ }++ /**+ * Refill tokens based on time elapsed+ */+ private refill(): void {+ const now = Date.now();+ const elapsed = now - this.lastRefill;+ const tokensToAdd = elapsed * this.refillRate;++ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);+ this.lastRefill = now;+ }++ /**+ * Wait for a token to become available+ */+ async acquire(): Promise<void> {+ this.refill();++ if (this.tokens >= 1) {+ this.tokens -= 1;+ return;+ }++ // Calculate wait time+ const tokensNeeded = 1 - this.tokens;+ const waitMs = Math.ceil(tokensNeeded / this.refillRate);++ await new Promise(resolve => setTimeout(resolve, Math.max(waitMs, this.retryAfterMs)));++ // Try again+ return this.acquire();+ }++ /**+ * Try to acquire without waiting+ */+ tryAcquire(): boolean {+ this.refill();++ if (this.tokens >= 1) {+ this.tokens -= 1;+ return true;+ }++ return false;+ }++ /**+ * Get current token count+ */+ getAvailableTokens(): number {+ this.refill();+ return Math.floor(this.tokens);+ }++ /**+ * Get time until next token is available+ */+ getWaitTime(): number {+ this.refill();++ if (this.tokens >= 1) {+ return 0;+ }++ const tokensNeeded = 1 - this.tokens;+ return Math.ceil(tokensNeeded / this.refillRate);+ }+}++/**+ * Reddit-specific rate limiter+ * 60 requests per minute with burst allowance+ */+export class RedditRateLimiter extends RateLimiter {+ private consecutiveErrors: number = 0;+ private backoffUntil: number = 0;++ constructor() {+ super({+ maxRequests: 60,+ windowMs: 60000, // 1 minute+ retryAfterMs: 1000+ });+ }++ /**+ * Acquire with exponential backoff on errors+ */+ async acquireWithBackoff(): Promise<void> {+ // Check if we're in backoff period+ const now = Date.now();+ if (now < this.backoffUntil) {+ const waitMs = this.backoffUntil - now;+ await new Promise(resolve => setTimeout(resolve, waitMs));+ }++ await this.acquire();+ }++ /**+ * Report a successful request+ */+ reportSuccess(): void {+ this.consecutiveErrors = 0;+ }++ /**+ * Report a rate limit error (429)+ */+ reportRateLimit(): void {+ this.consecutiveErrors++;+ // Exponential backoff: 2^n seconds, max 5 minutes+ const backoffSeconds = Math.min(Math.pow(2, this.consecutiveErrors), 300);+ this.backoffUntil = Date.now() + backoffSeconds * 1000;++ console.warn(`Rate limited. Backing off for ${backoffSeconds}s`);+ }++ /**+ * Report a general error+ */+ reportError(): void {+ this.consecutiveErrors++;+ // Linear backoff for non-rate-limit errors+ const backoffSeconds = Math.min(this.consecutiveErrors * 2, 30);+ this.backoffUntil = Date.now() + backoffSeconds * 1000;+ }++ /**+ * Reset error state+ */+ reset(): void {+ this.consecutiveErrors = 0;+ this.backoffUntil = 0;+ }+}++// Global Reddit rate limiter instance+let redditLimiter: RedditRateLimiter | null = null;++/**+ * Get the global Reddit rate limiter+ */+export function getRedditRateLimiter(): RedditRateLimiter {+ if (!redditLimiter) {+ redditLimiter = new RedditRateLimiter();+ }+ return redditLimiter;+}++/**+ * Throttle function calls+ */+export function throttle<T extends (...args: any[]) => Promise<any>>(+ fn: T,+ limiter: RateLimiter+): T {+ return (async (...args: Parameters<T>) => {+ await limiter.acquire();+ return fn(...args);+ }) as T;+}++/**+ * Retry with exponential backoff+ */+export async function retryWithBackoff<T>(+ fn: () => Promise<T>,+ options: {+ maxRetries?: number;+ initialDelayMs?: number;+ maxDelayMs?: number;+ onRetry?: (error: Error, attempt: number) => void;+ } = {}+): Promise<T> {+ const {+ maxRetries = 3,+ initialDelayMs = 1000,+ maxDelayMs = 30000,+ onRetry+ } = options;++ let lastError: Error;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ return await fn();+ } catch (error) {+ lastError = error as Error;++ if (attempt < maxRetries) {+ const delay = Math.min(initialDelayMs * Math.pow(2, attempt), maxDelayMs);+ onRetry?.(lastError, attempt + 1);+ await new Promise(resolve => setTimeout(resolve, delay));+ }+ }+ }++ throw lastError!;+}diff --git a/agents/reddit-research/store_to_notion.py b/agents/reddit-research/store_to_notion.pynew file mode 100644index 0000000..41f3221--- /dev/null+++ b/agents/reddit-research/store_to_notion.py@@ -0,0 +1,95 @@+#!/usr/bin/env python3+"""+Store Reddit Research to Notion+Creates a Notion page with extracted insights from Reddit threads.++Usage:+ python store_to_notion.py <json_file> --page-id <notion_page_id>++The json file should be output from reddit_extractor.py --json+"""++import json+import subprocess+import sys+from datetime import datetime+++def create_notion_page(data: dict, parent_page_id: str) -> str:+ """Create a Notion page with the research data using claude CLI."""++ post = data['post']+ metrics = data['metrics']+ top_comments = data.get('top_comments', [])[:10]++ # Build Notion-flavored markdown content+ content_lines = [+ f"**Source:** [{post['subreddit']}]({post['url']})",+ f"**Extracted:** {data.get('extracted_at', datetime.now().isoformat())}",+ "",+ "## Metrics",+ f"- Post Score: {post['score']}",+ f"- Upvote Ratio: {post['upvote_ratio']:.0%}" if post.get('upvote_ratio') else "",+ f"- Total Comments: {metrics['total_comments']}",+ f"- Unique Authors: {metrics['unique_authors']}",+ f"- Avg Comment Score: {metrics['avg_comment_score']}",+ "",+ "## Original Post",+ "",+ post.get('selftext', '*No content*')[:2000],+ "",+ "## Top Comments",+ "",+ ]++ for c in top_comments:+ content_lines.append(f"### [{c['score']} pts] u/{c['author']}")+ content_lines.append(c['body'][:500])+ content_lines.append("")++ content = '\n'.join(content_lines)++ # Build the MCP command+ mcp_command = {+ "parent": {"page_id": parent_page_id},+ "pages": [{+ "properties": {"title": f"π {post['title'][:80]}"},+ "content": content+ }]+ }++ print(f"Creating Notion page: {post['title'][:50]}...")+ print(json.dumps(mcp_command, indent=2))++ return mcp_command+++def main():+ if len(sys.argv) < 2:+ print("Usage: python store_to_notion.py <json_file> [--page-id <notion_page_id>]")+ sys.exit(1)++ json_file = sys.argv[1]+ page_id = None++ if '--page-id' in sys.argv:+ idx = sys.argv.index('--page-id')+ if idx + 1 < len(sys.argv):+ page_id = sys.argv[idx + 1]++ with open(json_file, 'r') as f:+ data = json.load(f)++ if page_id:+ command = create_notion_page(data, page_id)+ # Output the command - user can then use it with MCP+ print("\nβ Ready to create Notion page. Use the above JSON with notion-create-pages MCP tool.")+ else:+ print("Note: No --page-id provided. Outputting preview only.")+ print(f"\nThread: {data['post']['title']}")+ print(f"Comments: {data['metrics']['total_comments']}")+ print(f"Top comment authors: {', '.join(c['author'] for c in data.get('top_comments', [])[:5])}")+++if __name__ == '__main__':+ main()diff --git a/agents/reddit-research/tsconfig.json b/agents/reddit-research/tsconfig.jsonnew file mode 100644index 0000000..a5589ed--- /dev/null+++ b/agents/reddit-research/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022"],+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist", "tests"]+}