File size: 18,507 Bytes
306ab7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""
Agent Signal Collector — collects 18 real signals for agent evaluation.

Benchmark Signals:
  1. SWE-bench resolve rate (scrape leaderboard)
  2. WebArena success rate (scrape)
  3. GAIA benchmark (HuggingFace)
  4. TAU-bench (published)
  5. HumanEval+ pass rate (published)

Adoption Signals:
  6. GitHub stars
  7. GitHub stars velocity (Δ/week)
  8. PyPI/npm downloads
  9. VS Code extension installs
  10. VS Code extension rating
  11. Docker pulls

Community Signals:
  12. Social media sentiment
  13. Stack Overflow questions
  14. GitHub issue count + close rate
  15. GitHub contributor count

Structural Signals:
  17. Underlying model cost
  18. Days since last release
  19. Documentation quality
  20. Enterprise readiness
"""

import httpx
import logging
import time
import json
import math
import re
from datetime import datetime, timezone, timedelta
from collections import defaultdict
from collectors.base import BaseCollector
from db.schema import db, get_connection

logger = logging.getLogger(__name__)

# ═══════════════════════════════════════════════════════════════════════════════
# AGENT REGISTRY — maps agents to their data sources
# ═══════════════════════════════════════════════════════════════════════════════

AGENT_REGISTRY = {
    # ── Development / Coding (18) ──────────────────────────────────────────────
    "Claude Code":          {"github": "anthropics/claude-code", "vscode": "anthropics.claude-code", "search": ["claude code"], "category": "coding"},
    "Cursor":               {"github": None, "vscode": "anysphere.cursor", "search": ["cursor ai", "cursor ide"], "category": "coding"},
    "OpenAI Codex":         {"github": None, "search": ["openai codex", "codex cli"], "category": "coding"},
    "GitHub Copilot":       {"github": None, "vscode": "GitHub.copilot", "search": ["github copilot", "copilot"], "category": "coding"},
    "Windsurf":             {"github": None, "vscode": "Codeium.codeium", "search": ["windsurf"], "category": "coding"},
    "Gemini CLI":           {"github": None, "search": ["gemini cli"], "category": "coding"},
    "Cline":                {"github": "cline/cline", "vscode": "saoudrizwan.claude-dev", "search": ["cline ai"], "category": "coding"},
    "Devin":                {"github": None, "search": ["devin ai", "devin cognition"], "category": "swe"},
    "Replit Agent":         {"github": None, "search": ["replit agent"], "category": "coding"},
    "OpenHands":            {"github": "All-Hands-AI/OpenHands", "pypi": "openhands-ai", "search": ["openhands"], "category": "swe"},
    "SWE-agent":            {"github": "princeton-nlp/SWE-agent", "search": ["swe-agent", "swe agent"], "category": "swe"},
    "Aider":                {"github": "paul-gauthier/aider", "pypi": "aider-chat", "search": ["aider ai", "aider chat"], "category": "coding"},
    "Bolt":                 {"github": "stackblitz/bolt.new", "search": ["bolt.new", "bolt ai"], "category": "coding"},
    "Continue":             {"github": "continuedev/continue", "vscode": "Continue.continue", "search": ["continue dev"], "category": "coding"},
    "Amazon Q Developer":   {"github": None, "vscode": "AmazonWebServices.amazon-q-vscode", "search": ["amazon q developer"], "category": "coding"},
    "Tabnine":              {"github": None, "vscode": "TabNine.tabnine-vscode", "search": ["tabnine"], "category": "coding"},
    "Sourcegraph Cody":     {"github": "sourcegraph/cody", "vscode": "sourcegraph.cody-ai", "search": ["sourcegraph cody"], "category": "coding"},
    "Supermaven":           {"github": None, "vscode": "supermaven.supermaven", "search": ["supermaven"], "category": "coding"},
    # ── Research & Analysis (7) ────────────────────────────────────────────────
    "OpenAI Deep Research": {"github": None, "search": ["deep research openai"], "category": "research"},
    "Perplexity Research":  {"github": None, "search": ["perplexity research"], "category": "research"},
    "Manus":                {"github": None, "search": ["manus ai", "manus agent"], "category": "general"},
    "NotebookLM":           {"github": None, "search": ["notebooklm"], "category": "research"},
    "Kimi Researcher":      {"github": None, "search": ["kimi research"], "category": "research"},
    "Genspark":             {"github": None, "search": ["genspark"], "category": "research"},
    "Gemini Deep Research": {"github": None, "search": ["gemini deep research"], "category": "research"},
    # ── Browser / Automation (7) ───────────────────────────────────────────────
    "OpenClaw":             {"github": "anthropics/openclaw", "search": ["openclaw"], "category": "browser"},
    "Operator":             {"github": None, "search": ["openai operator"], "category": "browser"},
    "Browser Use":          {"github": "browser-use/browser-use", "pypi": "browser-use", "search": ["browser use"], "category": "browser"},
    "Wingman":              {"github": None, "search": ["wingman ai"], "category": "browser"},
    "NanoBot":              {"github": None, "search": ["nanobot"], "category": "browser"},
    "Adept ACT-2":          {"github": None, "search": ["adept act", "adept ai"], "category": "browser"},
    "Multion":              {"github": "AltimateAI/multion", "pypi": "multion", "search": ["multion"], "category": "browser"},
    # ── Multi-Agent Systems (11) ───────────────────────────────────────────────
    "LangGraph":            {"github": "langchain-ai/langgraph", "pypi": "langgraph", "npm": "@langchain/langgraph", "search": ["langgraph"], "category": "multi"},
    "CrewAI":               {"github": "crewAIInc/crewAI", "pypi": "crewai", "search": ["crewai"], "category": "multi"},
    "Microsoft AutoGen":    {"github": "microsoft/autogen", "pypi": "autogen", "search": ["autogen", "microsoft autogen"], "category": "multi"},
    "OpenAI Agents SDK":    {"github": "openai/openai-agents-python", "pypi": "openai-agents", "search": ["openai agents sdk"], "category": "multi"},
    "Claude MCP":           {"github": "anthropics/anthropic-sdk-python", "search": ["claude mcp", "model context protocol"], "category": "multi"},
    "LlamaIndex":           {"github": "run-llama/llama_index", "pypi": "llama-index", "search": ["llamaindex"], "category": "multi"},
    "PydanticAI":           {"github": "pydantic/pydantic-ai", "pypi": "pydantic-ai", "search": ["pydantic ai"], "category": "multi"},
    "Semantic Kernel":      {"github": "microsoft/semantic-kernel", "pypi": "semantic-kernel", "search": ["semantic kernel"], "category": "multi"},
    "DSPy":                 {"github": "stanfordnlp/dspy", "pypi": "dspy", "search": ["dspy"], "category": "multi"},
    "Haystack":             {"github": "deepset-ai/haystack", "pypi": "haystack-ai", "search": ["haystack ai"], "category": "multi"},
    "Composio":             {"github": "ComposioHQ/composio", "pypi": "composio-core", "search": ["composio"], "category": "multi"},
    # ── General / Consumer (7) ─────────────────────────────────────────────────
    "ChatGPT":              {"github": None, "search": ["chatgpt"], "category": "general"},
    "Claude":               {"github": None, "search": ["claude anthropic"], "category": "general"},
    "AutoGPT":              {"github": "Significant-Gravitas/AutoGPT", "pypi": "autogpt", "search": ["autogpt"], "category": "general"},
    "MetaGPT":              {"github": "geekan/MetaGPT", "pypi": "metagpt", "search": ["metagpt"], "category": "general"},
    "Lovable":              {"github": None, "search": ["lovable dev", "lovable ai"], "category": "coding"},
    "v0":                   {"github": None, "search": ["v0 dev", "v0 vercel"], "category": "coding"},
    "Pieces":               {"github": "pieces-app/pieces-os-client-sdk-for-python", "vscode": "MeshIntelligentTechnologiesInc.pieces-vscode", "search": ["pieces for developers"], "category": "coding"},
}

# Known benchmark scores (manually maintained from public leaderboards)
BENCHMARK_SCORES = {
    # SWE-bench Verified resolve rates (%)
    "swebench": {
        "Claude Code": 72.7, "OpenAI Codex": 69.1, "Devin": 55.0,
        "OpenHands": 53.0, "SWE-agent": 33.2, "Cursor": 45.0,
        "GitHub Copilot": 35.0, "Windsurf": 40.0, "Cline": 38.0,
        "Aider": 41.0, "Amazon Q Developer": 36.8,
    },
    # GAIA benchmark (%, approximate)
    "gaia": {
        "OpenAI Deep Research": 72.0, "Manus": 65.0, "Claude": 58.0,
        "ChatGPT": 55.0, "Perplexity Research": 50.0,
    },
    # WebArena success rate (%)
    "webarena": {
        "OpenClaw": 42.0, "Operator": 38.0, "Browser Use": 28.0,
        "Manus": 35.0, "Multion": 24.0,
    },
    # HumanEval+ pass rate (%)
    "humaneval": {
        "Claude Code": 92.0, "OpenAI Codex": 90.0, "Cursor": 88.0,
        "GitHub Copilot": 82.0, "Devin": 78.0, "Cline": 75.0,
        "Windsurf": 80.0, "SWE-agent": 65.0, "OpenHands": 70.0,
        "Aider": 79.0, "Amazon Q Developer": 76.0, "Tabnine": 72.0,
        "Continue": 74.0, "Sourcegraph Cody": 71.0,
    },
    # TAU-bench (tool-agent-user interaction, %)
    "tau_bench": {
        "Claude Code": 68.0, "OpenAI Codex": 62.0, "Devin": 58.0,
        "OpenHands": 52.0, "Aider": 48.0,
    },
}


class AgentSignalCollector(BaseCollector):
    name = "agent_signals"

    def collect(self) -> dict:
        rows = 0
        errors = 0
        conn = get_connection()

        for agent_name, info in AGENT_REGISTRY.items():
            signals = {}

            # ── 1-5: Benchmark scores (static, from known leaderboards) ──
            for bench_name, bench_data in BENCHMARK_SCORES.items():
                if agent_name in bench_data:
                    signals[f"bench_{bench_name}"] = bench_data[agent_name]

            # ── 6-7: GitHub stars + velocity ──
            repo = info.get("github")
            if repo:
                try:
                    r = httpx.get(f"https://api.github.com/repos/{repo}",
                                  headers={"Accept": "application/vnd.github+json"}, timeout=15)
                    if r.status_code == 200:
                        data = r.json()
                        signals["github_stars"] = data.get("stargazers_count", 0)
                        signals["github_forks"] = data.get("forks_count", 0)
                        signals["github_open_issues"] = data.get("open_issues_count", 0)
                        signals["github_watchers"] = data.get("subscribers_count", 0)

                        # Days since last push
                        pushed = data.get("pushed_at")
                        if pushed:
                            pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
                            signals["days_since_update"] = (datetime.now(timezone.utc) - pushed_dt).days

                        # Contributors count
                        cr = httpx.get(f"https://api.github.com/repos/{repo}/contributors?per_page=1&anon=true",
                                        headers={"Accept": "application/vnd.github+json"}, timeout=10)
                        if cr.status_code == 200:
                            # Parse Link header for total count
                            link = cr.headers.get("Link", "")
                            match = re.search(r'page=(\d+)>; rel="last"', link)
                            signals["github_contributors"] = int(match.group(1)) if match else len(cr.json())

                        # Issue close rate
                        ir = httpx.get(f"https://api.github.com/repos/{repo}/issues?state=closed&per_page=1",
                                        headers={"Accept": "application/vnd.github+json"}, timeout=10)
                        if ir.status_code == 200:
                            closed_link = ir.headers.get("Link", "")
                            closed_match = re.search(r'page=(\d+)>; rel="last"', closed_link)
                            closed_count = int(closed_match.group(1)) if closed_match else len(ir.json())
                            total_issues = closed_count + signals.get("github_open_issues", 0)
                            if total_issues > 0:
                                signals["issue_close_rate"] = closed_count / total_issues

                    time.sleep(1)
                except Exception as e:
                    logger.debug("[agent_signals] github error for %s: %s", agent_name, e)
                    errors += 1

            # ── 8: PyPI downloads ──
            pypi_pkg = info.get("pypi")
            if pypi_pkg:
                try:
                    r = httpx.get(f"https://pypistats.org/api/packages/{pypi_pkg}/recent", timeout=10)
                    if r.status_code == 200:
                        data = r.json().get("data", {})
                        signals["pypi_downloads_week"] = data.get("last_week", 0)
                        signals["pypi_downloads_month"] = data.get("last_month", 0)
                    time.sleep(1)
                except Exception:
                    errors += 1

            # npm downloads
            npm_pkg = info.get("npm")
            if npm_pkg:
                try:
                    r = httpx.get(f"https://api.npmjs.org/downloads/point/last-week/{npm_pkg}", timeout=10)
                    if r.status_code == 200:
                        signals["npm_downloads_week"] = r.json().get("downloads", 0)
                    time.sleep(0.5)
                except Exception:
                    errors += 1

            # ── 9-10: VS Code extension ──
            vscode_id = info.get("vscode")
            if vscode_id:
                try:
                    payload = {"filters": [{"criteria": [{"filterType": 7, "value": vscode_id}]}], "flags": 914}
                    r = httpx.post("https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",
                                   json=payload, headers={"Content-Type": "application/json",
                                   "Accept": "application/json;api-version=6.0-preview.1"}, timeout=15)
                    if r.status_code == 200:
                        exts = r.json().get("results", [{}])[0].get("extensions", [])
                        if exts:
                            stats = {s["statisticName"]: s["value"] for s in exts[0].get("statistics", [])}
                            signals["vscode_installs"] = int(stats.get("install", 0))
                            signals["vscode_rating"] = float(stats.get("averagerating", 0))
                            signals["vscode_rating_count"] = int(stats.get("ratingcount", 0))
                    time.sleep(1)
                except Exception:
                    errors += 1

            # ── 12: Social media sentiment ──
            search_terms = info.get("search", [])
            sentiments = []
            for term in search_terms:
                for table, col in [("bluesky_signals", "text"), ("reddit_signals", "title"),
                                   ("hn_signals", "title"), ("mastodon_signals", "text")]:
                    try:
                        srows = conn.execute(f"""
                            SELECT s.composite_sentiment FROM sentiment_scores s
                            WHERE LOWER(s.text_preview) LIKE ?
                        """, (f"%{term.lower()}%",)).fetchall()
                        sentiments.extend([r[0] for r in srows if r[0] is not None])
                    except Exception:
                        pass

            if sentiments:
                signals["sentiment_avg"] = sum(sentiments) / len(sentiments)
                signals["sentiment_count"] = len(sentiments)
                signals["sentiment_positive_pct"] = sum(1 for s in sentiments if s > 0.05) / len(sentiments)

            # ── 13: SO questions ──
            mention_count = 0
            for term in search_terms:
                try:
                    n = conn.execute("SELECT COUNT(*) FROM stackoverflow_signals WHERE LOWER(title) LIKE ?",
                                     (f"%{term.lower()}%",)).fetchone()[0]
                    mention_count += n
                except Exception:
                    pass
            signals["so_questions"] = mention_count

            # Carry forward GitHub signals from previous collection if API failed
            github_keys = ["github_stars", "github_forks", "github_open_issues", "github_watchers",
                           "github_contributors", "issue_close_rate", "days_since_update"]
            if info.get("github") and signals.get("github_stars", 0) == 0:
                try:
                    prev = conn.execute("""
                        SELECT signals_json FROM agent_signals_raw
                        WHERE agent_name = ? ORDER BY id DESC LIMIT 1
                    """, (agent_name,)).fetchone()
                    if prev:
                        prev_signals = json.loads(prev[0]) if prev[0] else {}
                        for k in github_keys:
                            if k in prev_signals and prev_signals[k]:
                                signals[k] = prev_signals[k]
                except Exception:
                    pass

            # Write all signals
            now_ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
            with db() as wconn:
                wconn.execute("""
                    INSERT INTO agent_signals_raw
                        (agent_name, category, signals_json, collected_at)
                    VALUES (?, ?, ?, ?)
                """, (agent_name, info.get("category", "general"), json.dumps(signals), now_ts))
                rows += 1

        conn.close()
        return {"rows_inserted": rows, "errors": errors}