forked from jiayaoqijia/cryptoskill
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto-update.py
More file actions
executable file
·1395 lines (1156 loc) · 53.8 KB
/
auto-update.py
File metadata and controls
executable file
·1395 lines (1156 loc) · 53.8 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""CryptoSkill Auto-Update Bot
Multi-source discovery of new crypto skills:
1. OpenClaw skills repo (local scan)
2. Web/Twitter search via AltLLM (AI-powered discovery)
3. Official GitHub repos (priority scanning)
Includes security checks to reject malicious skills.
"""
import argparse
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.request
import urllib.error
from datetime import datetime, timedelta, timezone
from pathlib import Path
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPTS_DIR = REPO_ROOT / "scripts"
SKILLS_DIR = REPO_ROOT / "skills"
DOCS_DIR = REPO_ROOT / "docs"
SKILLS_JSON = DOCS_DIR / "skills.json"
INDEX_HTML = DOCS_DIR / "index.html"
ENV_FILE = REPO_ROOT / ".env"
WATCHLIST_FILE = SCRIPTS_DIR / "watchlist.json"
REPO_SHAS_FILE = SCRIPTS_DIR / ".repo-shas.json"
LOOKBACK_DAYS = 7
ALTLLM_BASE_URLS = [
"https://api.altllm.ai/v1",
"https://altllm-api.viber.autonome.fun/v1",
]
ALTLLM_MODEL = "altllm-standard"
# Official GitHub repos to check for new/updated skills (highest priority)
OFFICIAL_REPOS = [
{"org": "binance", "repo": "binance-skills-hub", "category": "exchanges", "prefix": "binance-official-", "skills_dir": "skills"},
{"org": "okx", "repo": "onchainos-skills", "category": "exchanges", "prefix": "okx-official-", "skills_dir": "skills"},
{"org": "okx", "repo": "agent-skills", "category": "exchanges", "prefix": "okx-official-", "skills_dir": "skills"},
{"org": "BitgetLimited", "repo": "agent_hub", "category": "exchanges", "prefix": "bitget-official-", "skills_dir": "skills"},
{"org": "Kucoin", "repo": "kucoin-skills-hub", "category": "exchanges", "prefix": "kucoin-official-", "skills_dir": "skills"},
{"org": "krakenfx", "repo": "kraken-cli", "category": "exchanges", "prefix": "kraken-official-", "skills_dir": "skills"},
{"org": "Uniswap", "repo": "uniswap-ai", "category": "defi", "prefix": "uniswap-official-", "skills_dir": "skills"},
{"org": "bnb-chain", "repo": "bnbchain-skills", "category": "chains", "prefix": "bnb-official-", "skills_dir": "skills"},
{"org": "coinbase", "repo": "agentkit", "category": "mcp-servers", "prefix": "coinbase-"},
{"org": "alchemyplatform", "repo": "alchemy-mcp-server", "category": "mcp-servers", "prefix": "alchemy-"},
{"org": "solana-foundation", "repo": "solana-mcp-official", "category": "mcp-servers", "prefix": "solana-"},
{"org": "base", "repo": "base-mcp", "category": "mcp-servers", "prefix": "base-"},
{"org": "monad-developers", "repo": "monad-mcp", "category": "mcp-servers", "prefix": "monad-"},
{"org": "aptos-labs", "repo": "aptos-npm-mcp", "category": "mcp-servers", "prefix": "aptos-"},
{"org": "blockscout", "repo": "mcp-server", "category": "mcp-servers", "prefix": "blockscout-"},
{"org": "nearai", "repo": "near-mcp", "category": "mcp-servers", "prefix": "near-"},
{"org": "coingecko", "repo": "coingecko-typescript", "category": "mcp-servers", "prefix": "coingecko-"},
]
# GitHub search queries to discover NEW official crypto skill/MCP repos
GITHUB_SEARCH_QUERIES = [
"crypto MCP server official language:TypeScript pushed:>{cutoff}",
"blockchain skills agent official language:TypeScript pushed:>{cutoff}",
"crypto agent skills language:Python pushed:>{cutoff}",
"DeFi MCP server pushed:>{cutoff}",
]
# Crypto keyword buckets for detection and categorisation
KEYWORDS = {
"exchanges": [
"binance", "okx", "coinbase", "kraken", "bybit", "gate", "bitget",
"kucoin", "mexc", "hyperliquid", "bitfinex", "crypto.com",
],
"chains": [
"ethereum", "solana", "bitcoin", "polygon", "arbitrum", "base", "sui",
"aptos", "monad", "ton", "near", "tron", "starknet", "zksync",
"avalanche", "cosmos", "polkadot", "cardano", "hedera", "stellar",
"lightning", "filecoin", "sei", "mantle", "celestia", "blast",
],
"defi": [
"defi", "swap", "uniswap", "aave", "lido", "compound", "makerdao",
"curve", "pancakeswap", "raydium", "jupiter", "pump", "sushiswap",
"opensea", "lending", "liquidity", "yield", "amm",
],
"trading": [
"trading", "bot", "signal", "arbitrage", "grid", "dca", "whale",
"sniper", "mev", "alpha",
],
"analytics": [
"dune", "coingecko", "coinmarketcap", "etherscan", "nansen",
"defillama", "thegraph", "zapper", "zerion", "debank",
],
"wallets": ["wallet", "metamask", "phantom", "ledger", "trezor", "mpc"],
"payments": ["x402", "payment", "micropayment"],
"prediction-markets": ["polymarket", "prediction"],
"social": ["farcaster", "nostr", "xmtp", "lens"],
"ai-crypto": ["bittensor", "virtuals", "eliza", "ai-agent", "ai agent"],
"identity": ["8004", "erc-8004", "identity", "did"],
"mcp-servers": ["mcp server", "mcp-server"],
}
ALL_CRYPTO_KEYWORDS = []
for kws in KEYWORDS.values():
ALL_CRYPTO_KEYWORDS.extend(kws)
ALL_CRYPTO_KEYWORDS.extend([
"crypto", "blockchain", "token", "nft", "staking", "bridge", "oracle",
"moralis", "alchemy", "foundry", "hardhat", "wagmi", "viem", "web3",
"on-chain", "onchain",
])
# Security: suspicious patterns to flag
SECURITY_PATTERNS = [
# Exfiltration
(r'curl\s+.*\|.*sh', "Remote code execution via curl pipe"),
(r'wget\s+.*\|.*sh', "Remote code execution via wget pipe"),
(r'eval\s*\(', "Eval usage (potential code injection)"),
(r'exec\s*\(', "Exec usage (potential code injection)"),
(r'os\.system\s*\(', "os.system call (potential command injection)"),
(r'subprocess\.(call|run|Popen)\s*\(', "Subprocess call (potential command injection)"),
# Credential theft
(r'\.env', "References .env file (potential credential access)"),
(r'api[_-]?key\s*=\s*["\'][a-zA-Z0-9]{20,}', "Hardcoded API key"),
(r'private[_-]?key\s*=\s*["\'][a-fA-F0-9]{64}', "Hardcoded private key"),
(r'mnemonic|seed\s*phrase', "References seed phrase/mnemonic"),
# Network exfiltration
(r'https?://[^\s"\']+\.(tk|ml|ga|cf|gq)/', "Suspicious TLD in URL"),
(r'ngrok\.io', "Ngrok tunnel (potential data exfiltration)"),
(r'webhook\.site', "Webhook.site (potential data exfiltration)"),
(r'requestbin', "RequestBin (potential data exfiltration)"),
# Obfuscation
(r'base64\.(b64decode|decode)', "Base64 decode (potential obfuscation)"),
(r'\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){5,}', "Hex-encoded strings (obfuscation)"),
(r'fromCharCode', "fromCharCode (JavaScript obfuscation)"),
(r'atob\s*\(', "atob (JavaScript base64 decode)"),
# Prompt injection
(r'ignore\s+(?:all\s+)?previous\s+instructions', "Prompt injection attempt"),
(r'system\s*:\s*you\s+are', "System prompt override attempt"),
(r'<\s*system\s*>', "System tag injection"),
]
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("auto-update")
# ---------------------------------------------------------------------------
# Load .env
# ---------------------------------------------------------------------------
def load_env():
"""Load .env file into os.environ."""
if ENV_FILE.exists():
for line in ENV_FILE.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, val = line.split("=", 1)
os.environ.setdefault(key.strip(), val.strip())
# ---------------------------------------------------------------------------
# AltLLM Client
# ---------------------------------------------------------------------------
def altllm_chat(prompt: str, system: str = "", max_tokens: int = 2000) -> str:
"""Call AltLLM chat completions API."""
api_key = os.environ.get("ALTLLM") or os.environ.get("ALTLLM_API_KEY")
if not api_key:
log.warning("No ALTLLM API key found - skipping AI-powered search")
return ""
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
payload = json.dumps({
"model": ALTLLM_MODEL,
"messages": messages,
"max_tokens": max_tokens,
"temperature": 0.3,
}).encode("utf-8")
base_url = os.environ.get("ALTLLM_BASE_URL", "")
urls_to_try = [base_url] if base_url else ALTLLM_BASE_URLS
for base in urls_to_try:
req = urllib.request.Request(
f"{base}/chat/completions",
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"User-Agent": "CryptoSkill-Bot/1.0",
"Accept": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.loads(resp.read().decode("utf-8"))
msg = data["choices"][0]["message"]
return msg.get("content") or msg.get("reasoning_content") or ""
except (urllib.error.URLError, urllib.error.HTTPError, KeyError, IndexError) as e:
log.warning("AltLLM API call to %s failed: %s", base, e)
continue
return ""
# ---------------------------------------------------------------------------
# Security Scanner
# ---------------------------------------------------------------------------
def scan_skill_security(skill_dir: Path) -> list[dict]:
"""Scan all text files in a skill directory for security issues.
Returns list of {file, line, pattern, reason} dicts.
"""
issues = []
for fpath in skill_dir.rglob("*"):
if not fpath.is_file():
continue
# Skip binary files
if fpath.suffix in (".png", ".jpg", ".gif", ".ico", ".woff", ".woff2", ".ttf"):
continue
try:
content = fpath.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
for line_num, line in enumerate(content.splitlines(), 1):
for pattern, reason in SECURITY_PATTERNS:
if re.search(pattern, line, re.IGNORECASE):
issues.append({
"file": str(fpath.relative_to(skill_dir)),
"line": line_num,
"pattern": pattern,
"reason": reason,
"content": line.strip()[:120],
})
return issues
def ai_security_review(skill_name: str, skill_content: str) -> dict:
"""Use AltLLM to perform an AI-powered security review of a skill.
Returns {"safe": bool, "score": int 0-10, "issues": [str], "summary": str}
"""
if not skill_content.strip():
return {"safe": True, "score": 10, "issues": [], "summary": "Empty skill"}
# Truncate to avoid token limits
truncated = skill_content[:6000]
response = altllm_chat(
prompt=f"""Analyze this crypto AI agent skill for security issues.
Skill name: {skill_name}
Content:
```
{truncated}
```
Check for:
1. Credential theft (stealing API keys, private keys, seed phrases)
2. Remote code execution (curl|sh, eval, exec, subprocess)
3. Data exfiltration (sending data to external servers)
4. Prompt injection (overriding system prompts)
5. Malicious URLs or suspicious domains
6. Obfuscated code (base64, hex encoding)
7. Unauthorized fund transfers or wallet draining
8. Social engineering in instructions
Respond in this exact JSON format:
{{"safe": true/false, "score": 0-10, "issues": ["issue1", "issue2"], "summary": "one line summary"}}
Only output the JSON, nothing else.""",
system="You are a security auditor for AI agent skills. Be thorough but avoid false positives for legitimate API documentation.",
max_tokens=500,
)
if not response:
return {"safe": True, "score": 5, "issues": ["AI review unavailable"], "summary": "Skipped"}
try:
# Extract JSON from response
json_match = re.search(r'\{[^{}]*"safe"[^{}]*\}', response, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
return {
"safe": result.get("safe", True),
"score": result.get("score", 5),
"issues": result.get("issues", []),
"summary": result.get("summary", ""),
}
except (json.JSONDecodeError, AttributeError):
pass
return {"safe": True, "score": 5, "issues": ["Could not parse AI review"], "summary": response[:100]}
# ---------------------------------------------------------------------------
# Web/Twitter Search via AltLLM
# ---------------------------------------------------------------------------
def search_trending_crypto_skills() -> list[dict]:
"""Use AltLLM to discover trending crypto skills/tools from web and social media."""
log.info("Searching web for trending crypto skills via AltLLM...")
response = altllm_chat(
prompt=f"""Search for the latest trending crypto AI agent skills, MCP servers, and tools
that have been released or gained traction in the last 7 days (as of {datetime.now().strftime('%Y-%m-%d')}).
Look for:
1. New official skills from major crypto projects (Binance, OKX, Coinbase, etc.)
2. Trending crypto MCP servers on GitHub
3. New DeFi/DEX agent integrations
4. Hot crypto tools being discussed on Twitter/X
5. New blockchain protocol agent SDKs
6. Prediction market or AI x Crypto tools
For each skill/tool found, provide:
- name: kebab-case identifier
- displayName: human readable name
- description: one sentence
- category: one of [exchanges, chains, defi, trading, analytics, wallets, payments, prediction-markets, social, ai-crypto, identity, mcp-servers, dev-tools]
- source_url: GitHub repo URL or project website
- official: true if from the project's own team, false if community
Respond as a JSON array. Only include genuinely new and crypto-relevant tools.
Output ONLY the JSON array, nothing else.""",
system="You are a crypto researcher with real-time access to web and social media data. Focus on quality over quantity - only include tools that are genuinely new and useful.",
max_tokens=3000,
)
if not response:
return []
try:
# Extract JSON array from response
json_match = re.search(r'\[.*\]', response, re.DOTALL)
if json_match:
discoveries = json.loads(json_match.group())
validated = []
for item in discoveries:
if not isinstance(item, dict):
continue
if not item.get("name") or not item.get("description"):
continue
validated.append({
"name": item.get("name", "").strip(),
"displayName": item.get("displayName", item.get("name", "")),
"description": item.get("description", ""),
"category": item.get("category", "dev-tools"),
"source_url": item.get("source_url", ""),
"official": item.get("official", False),
"source": "altllm-web-search",
})
log.info("AltLLM discovered %d trending skills", len(validated))
return validated
except (json.JSONDecodeError, AttributeError) as e:
log.warning("Failed to parse AltLLM discoveries: %s", e)
return []
# ---------------------------------------------------------------------------
# Source 3: GitHub API Search (no API key needed for basic search)
# ---------------------------------------------------------------------------
def github_api_get(url: str) -> dict | list | None:
"""Make a GET request to GitHub API (unauthenticated, 60 req/hr)."""
req = urllib.request.Request(url, headers={"Accept": "application/vnd.github.v3+json", "User-Agent": "CryptoSkill-Bot"})
try:
with urllib.request.urlopen(req, timeout=15) as resp:
return json.loads(resp.read().decode("utf-8"))
except (urllib.error.URLError, urllib.error.HTTPError) as e:
log.warning("GitHub API failed for %s: %s", url, e)
return None
def search_github_for_new_repos(lookback_days: int) -> list[dict]:
"""Search GitHub for new crypto MCP/skill repos created recently."""
cutoff = (datetime.now(timezone.utc) - timedelta(days=lookback_days)).strftime("%Y-%m-%d")
discoveries = []
for query_tpl in GITHUB_SEARCH_QUERIES:
query = query_tpl.replace("{cutoff}", cutoff)
url = f"https://api.github.com/search/repositories?q={urllib.request.quote(query)}&sort=updated&per_page=10"
data = github_api_get(url)
if not data or "items" not in data:
continue
for repo in data["items"]:
name = repo.get("name", "")
full_name = repo.get("full_name", "")
description = repo.get("description", "") or ""
html_url = repo.get("html_url", "")
# Skip if already known
slug = name.lower().replace("_", "-")
blob = f"{name} {description}".lower()
if not text_matches_keywords(blob, ALL_CRYPTO_KEYWORDS):
continue
category = categorize_skill(slug, description)
discoveries.append({
"name": slug,
"displayName": name.replace("-", " ").replace("_", " ").title(),
"description": description[:200],
"category": category,
"source_url": html_url,
"official": False,
"source": "github-search",
"author": full_name.split("/")[0] if "/" in full_name else "unknown",
})
# Deduplicate
seen = set()
unique = []
for d in discoveries:
if d["name"] not in seen:
seen.add(d["name"])
unique.append(d)
log.info("GitHub search found %d new repos", len(unique))
return unique
# ---------------------------------------------------------------------------
# Source 4: Check Official Repos for New/Updated Skills (with SHA tracking)
# ---------------------------------------------------------------------------
def load_repo_shas() -> dict:
"""Load stored commit SHAs from .repo-shas.json."""
if REPO_SHAS_FILE.exists():
try:
return read_json(REPO_SHAS_FILE)
except (json.JSONDecodeError, OSError):
pass
return {}
def save_repo_shas(shas: dict) -> None:
"""Save commit SHAs to .repo-shas.json."""
write_json(REPO_SHAS_FILE, shas)
def get_latest_commit_sha(org: str, repo: str) -> str | None:
"""Fetch the latest commit SHA from GitHub API without cloning."""
url = f"https://api.github.com/repos/{org}/{repo}/commits?per_page=1"
data = github_api_get(url)
if data and isinstance(data, list) and len(data) > 0:
return data[0].get("sha")
return None
def check_official_repos_for_updates(dry_run: bool = False) -> tuple[list[dict], int]:
"""Clone official repos and check for new or updated skills.
Uses commit SHA tracking to avoid re-cloning repos that haven't changed.
Returns (new_skills, updated_count).
"""
new_skills = []
updated = 0
existing = existing_skill_names()
repo_shas = load_repo_shas()
shas_changed = False
for repo_info in OFFICIAL_REPOS:
org = repo_info["org"]
repo = repo_info["repo"]
category = repo_info["category"]
prefix = repo_info.get("prefix", "")
skills_dir_name = repo_info.get("skills_dir", "")
sha_key = f"{org}/{repo}"
# Check latest commit SHA via API before cloning
log.info("Checking %s/%s for updates...", org, repo)
latest_sha = get_latest_commit_sha(org, repo)
if latest_sha:
stored_sha = repo_shas.get(sha_key)
if stored_sha and stored_sha == latest_sha:
log.info(" %s/%s unchanged (SHA: %s), skipping clone", org, repo, latest_sha[:8])
continue
log.info(" %s/%s has new commits (SHA: %s -> %s)", org, repo,
(stored_sha or "none")[:8], latest_sha[:8])
else:
log.info(" Could not fetch SHA for %s/%s, will clone to check", org, repo)
clone_dir = Path(f"/tmp/cs-official-{org}-{repo}")
# Clone or pull
if clone_dir.exists():
shutil.rmtree(clone_dir)
result = subprocess.run(
["git", "clone", "--depth", "1", f"https://github.com/{org}/{repo}.git", str(clone_dir)],
capture_output=True, timeout=30,
)
if result.returncode != 0:
log.warning(" Failed to clone %s/%s", org, repo)
continue
# Find skills directory
skills_path = clone_dir / skills_dir_name if skills_dir_name else clone_dir
if skills_dir_name and not skills_path.is_dir():
# Try root
skills_path = clone_dir
# Scan for SKILL.md files
for skill_md in skills_path.rglob("SKILL.md"):
skill_dir = skill_md.parent
skill_name = skill_dir.name
dest_name = f"{prefix}{skill_name}" if prefix and not skill_name.startswith(prefix) else skill_name
dest_path = SKILLS_DIR / category / dest_name
if dest_name in existing and dest_path.exists():
# Check if content changed
try:
old_content = (dest_path / "SKILL.md").read_text(encoding="utf-8", errors="ignore")
new_content = skill_md.read_text(encoding="utf-8", errors="ignore")
if old_content.strip() != new_content.strip():
if dry_run:
log.info(" [DRY-RUN] Would update %s (content changed)", dest_name)
else:
# Update: copy new SKILL.md over
shutil.copy2(skill_md, dest_path / "SKILL.md")
# Copy any new reference files
for ref in skill_dir.rglob("*"):
if ref.is_file() and ref.name != "SOURCE.md":
rel = ref.relative_to(skill_dir)
target = dest_path / rel
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(ref, target)
log.info(" Updated %s", dest_name)
updated += 1
except OSError:
pass
continue
if dest_name in existing:
continue
# New skill
fm = parse_skill_md_frontmatter(skill_md)
new_skills.append({
"slug": dest_name,
"name": fm.get("name", dest_name),
"displayName": fm.get("name", dest_name).replace("-", " ").title(),
"description": fm.get("description", f"Official skill from {org}"),
"category": category,
"tags": ["official", category],
"author": org,
"version": fm.get("version", "1.0.0"),
"owner": org,
"source_path": str(skill_dir),
"source": "official-repo",
"official": True,
})
log.info(" New official skill: %s -> %s", dest_name, category)
# Cleanup
shutil.rmtree(clone_dir, ignore_errors=True)
# Save the SHA after successful processing
if latest_sha:
repo_shas[sha_key] = latest_sha
shas_changed = True
# Persist updated SHAs
if shas_changed and not dry_run:
save_repo_shas(repo_shas)
log.info("Saved updated repo SHAs to %s", REPO_SHAS_FILE)
return new_skills, updated
# ---------------------------------------------------------------------------
# Source 5: Watchlist scan — check "missing" projects for new repos
# ---------------------------------------------------------------------------
def scan_watchlist_for_new_repos() -> list[dict]:
"""Scan watchlist.json for projects with status=missing/watch and check their GitHub orgs."""
if not WATCHLIST_FILE.exists():
log.warning("Watchlist not found at %s", WATCHLIST_FILE)
return []
watchlist = read_json(WATCHLIST_FILE)
discoveries = []
checked = 0
for category_key, projects in watchlist.items():
if category_key.startswith("_"):
continue
if not isinstance(projects, list):
continue
for project in projects:
status = project.get("status", "")
github_org = project.get("github")
name = project.get("name", "")
if status not in ("missing", "watch") or not github_org:
continue
checked += 1
# Search this org for MCP/skills repos
url = f"https://api.github.com/search/repositories?q=org:{github_org}+(mcp+OR+skill+OR+agent)&sort=updated&per_page=5"
data = github_api_get(url)
if not data or "items" not in data:
continue
for repo in data["items"]:
repo_name = repo.get("name", "")
description = repo.get("description", "") or ""
html_url = repo.get("html_url", "")
full_name = repo.get("full_name", "")
# Filter for crypto-relevant repos
blob = f"{repo_name} {description}".lower()
if not any(kw in blob for kw in ["mcp", "skill", "agent", "trading", "swap", "wallet", "blockchain"]):
continue
slug = repo_name.lower().replace("_", "-")
skill_category = categorize_skill(slug, description)
discoveries.append({
"name": slug,
"displayName": f"{name} - {repo_name}",
"description": description[:200],
"category": skill_category,
"source_url": html_url,
"official": True,
"source": "watchlist-scan",
"author": github_org,
"project": name,
})
log.info(" [WATCHLIST] %s: found %s (%s)", name, repo_name, html_url)
log.info("Scanned %d watchlist projects, found %d new repos", checked, len(discoveries))
return discoveries
# ---------------------------------------------------------------------------
# Watchlist timestamp/status updater
# ---------------------------------------------------------------------------
def update_watchlist_after_scan(scanned_github_orgs: set, new_skill_orgs: set, dry_run: bool = False) -> None:
"""Update watchlist.json after a scan run.
- Set last_checked to today for any project whose GitHub org was scanned
- Change status from "missing" to "added" for projects where new skills were found
"""
if not WATCHLIST_FILE.exists():
return
watchlist = read_json(WATCHLIST_FILE)
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
changes = 0
for category_key, projects in watchlist.items():
if category_key.startswith("_"):
continue
if not isinstance(projects, list):
continue
for project in projects:
github_org = project.get("github")
if not github_org:
continue
# Update last_checked for any scanned org
if github_org in scanned_github_orgs:
if project.get("last_checked") != today:
project["last_checked"] = today
changes += 1
# Promote status from "missing" to "added" if new skills were found
if github_org in new_skill_orgs and project.get("status") == "missing":
project["status"] = "added"
project["last_checked"] = today
changes += 1
log.info(" [WATCHLIST] Promoted %s from missing -> added", project.get("name", github_org))
if changes > 0:
if dry_run:
log.info("[DRY-RUN] Would update %d entries in watchlist.json", changes)
else:
write_json(WATCHLIST_FILE, watchlist)
log.info("Updated %d entries in watchlist.json", changes)
else:
log.info("No watchlist changes needed")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def read_json(path: Path) -> dict:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
def write_json(path: Path, data: dict) -> None:
with open(path, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2, ensure_ascii=False)
fh.write("\n")
def parse_skill_md_frontmatter(path: Path) -> dict:
"""Return the YAML front-matter from a SKILL.md as a dict."""
try:
text = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
return {}
m = re.match(r"^---\s*\n(.*?)\n---", text, re.DOTALL)
if not m:
return {}
fm: dict = {}
current_list_key = None
for line in m.group(1).splitlines():
list_match = re.match(r"^\s+-\s+(.+)", line)
if list_match and current_list_key:
fm.setdefault(current_list_key, []).append(
list_match.group(1).strip().strip('"').strip("'")
)
continue
kv = re.match(r"^(\w[\w-]*):\s*(.*)", line)
if kv:
key = kv.group(1)
val = kv.group(2).strip().strip('"').strip("'")
if val:
fm[key] = val
current_list_key = None
else:
current_list_key = key
continue
current_list_key = None
return fm
def text_matches_keywords(text: str, keywords: list) -> bool:
lower = text.lower()
return any(kw in lower for kw in keywords)
def categorize_skill(name: str, description: str) -> str:
blob = f"{name} {description}".lower()
priority = [
"exchanges", "prediction-markets", "payments", "identity",
"social", "ai-crypto", "mcp-servers", "chains", "defi",
"analytics", "wallets", "trading",
]
for cat in priority:
if any(kw in blob for kw in KEYWORDS[cat]):
return cat
return "dev-tools"
def existing_skill_names() -> set:
names = set()
for cat_dir in SKILLS_DIR.iterdir():
if not cat_dir.is_dir():
continue
for skill_dir in cat_dir.iterdir():
if skill_dir.is_dir():
names.add(skill_dir.name)
return names
def generate_source_md(owner: str, slug: str, source_url: str = "", official: bool = False) -> str:
classification = "OFFICIAL" if official else "COMMUNITY"
source_line = f"- **Source**: {source_url}" if source_url else f"- **Source**: [ClawHub](https://clawhub.ai/skills/{owner}/{slug})"
return (
"# Source Attribution\n\n"
f"- **Original Author**: {owner}\n"
f"- **Original Slug**: {slug}\n"
f"{source_line}\n"
"- **License**: MIT-0\n"
f"- **Classification**: {classification}\n"
)
def make_display_name(slug: str) -> str:
return " ".join(w.capitalize() for w in slug.split("-"))
# ---------------------------------------------------------------------------
# Source 1: OpenClaw Skills Repo (local scan)
# ---------------------------------------------------------------------------
def find_new_openclaw_skills(source_dir: Path, lookback_days: int) -> list:
"""Walk the source skills repo and return new crypto skills."""
cutoff_ms = int(
(datetime.now(timezone.utc) - timedelta(days=lookback_days)).timestamp() * 1000
)
new_skills = []
existing = existing_skill_names()
if not source_dir.is_dir():
log.warning("Source directory does not exist: %s", source_dir)
return []
for owner_dir in sorted(source_dir.iterdir()):
if not owner_dir.is_dir():
continue
for skill_dir in sorted(owner_dir.iterdir()):
if not skill_dir.is_dir():
continue
meta_path = skill_dir / "_meta.json"
skill_md_path = skill_dir / "SKILL.md"
if not meta_path.exists():
continue
try:
meta = read_json(meta_path)
except (json.JSONDecodeError, OSError):
continue
slug = meta.get("slug", skill_dir.name)
if slug in existing:
continue
published_at = meta.get("latest", {}).get("publishedAt", 0)
if published_at < cutoff_ms:
continue
fm = {}
if skill_md_path.exists():
fm = parse_skill_md_frontmatter(skill_md_path)
name = fm.get("name", slug)
description = fm.get("description", meta.get("displayName", slug))
blob = f"{name} {description} {' '.join(fm.get('tags', []))}".lower()
if not text_matches_keywords(blob, ALL_CRYPTO_KEYWORDS):
continue
category = categorize_skill(name, description)
new_skills.append({
"slug": slug,
"name": name,
"displayName": meta.get("displayName", make_display_name(slug)),
"description": description,
"category": category,
"tags": fm.get("tags", []),
"author": meta.get("owner", fm.get("author", "unknown")),
"version": meta.get("latest", {}).get("version", fm.get("version", "1.0.0")),
"owner": meta.get("owner", "unknown"),
"source_path": str(skill_dir),
"source": "openclaw",
"official": False,
})
return new_skills
# ---------------------------------------------------------------------------
# Source 2: AltLLM Web/Twitter Discovery
# ---------------------------------------------------------------------------
def create_skill_from_discovery(discovery: dict, dry_run: bool = False) -> bool:
"""Create a minimal skill entry from an AltLLM discovery."""
slug = discovery["name"]
category = discovery.get("category", "dev-tools")
dst = SKILLS_DIR / category / slug
if dst.exists():
return False
if dry_run:
log.info("[DRY-RUN] Would create discovered skill: %s -> %s", slug, category)
return True
dst.mkdir(parents=True, exist_ok=True)
# Create SKILL.md
official_tag = "official" if discovery.get("official") else ""
tags_str = f" - {category}"
if official_tag:
tags_str += f"\n - official"
skill_md = f"""---
name: {slug}
description: "{discovery['description']}"
version: 1.0.0
metadata:
openclaw:
tags:
{tags_str}
source: "{discovery.get('source_url', '')}"
---
# {discovery['displayName']}
{discovery['description']}
## Source
- **Discovered via**: AltLLM web search ({datetime.now().strftime('%Y-%m-%d')})
- **URL**: {discovery.get('source_url', 'N/A')}
"""
(dst / "SKILL.md").write_text(skill_md, encoding="utf-8")
# Create SOURCE.md
source_md = generate_source_md(
owner=discovery.get("author", "discovered"),
slug=slug,
source_url=discovery.get("source_url", ""),
official=discovery.get("official", False),
)
(dst / "SOURCE.md").write_text(source_md, encoding="utf-8")
log.info("Created discovered skill: %s -> %s", slug, category)
return True
# ---------------------------------------------------------------------------
# Security gate
# ---------------------------------------------------------------------------
def run_security_checks(skills: list, use_ai: bool = True) -> list:
"""Run security checks on skills and return only safe ones.
Official skills get lighter checks (trusted sources).
Community skills get full static + AI analysis.
"""
safe_skills = []
blocked = 0
for skill in skills:
source_path = skill.get("source_path")
is_official = skill.get("official", False)
# Official skills from known repos get lighter checks
if is_official:
log.info(" [SECURITY] %s — OFFICIAL, trusted source", skill["slug"])
safe_skills.append(skill)
continue
# For skills with source paths (from OpenClaw), run static analysis
if source_path and Path(source_path).exists():
issues = scan_skill_security(Path(source_path))
# Filter out low-risk patterns for documentation-only skills
critical_issues = [i for i in issues if not i["reason"].startswith("References .env")]
if critical_issues:
log.warning(
" [SECURITY] %s — BLOCKED (%d issues):",
skill["slug"], len(critical_issues)
)
for issue in critical_issues[:3]:
log.warning(" %s:%d — %s", issue["file"], issue["line"], issue["reason"])
blocked += 1
continue
# AI review for skills with scripts
if use_ai and source_path:
skill_dir = Path(source_path)
script_files = list(skill_dir.rglob("*.py")) + list(skill_dir.rglob("*.sh")) + list(skill_dir.rglob("*.js"))
if script_files:
content = ""
for sf in script_files[:3]:
try:
content += f"\n--- {sf.name} ---\n"
content += sf.read_text(encoding="utf-8", errors="ignore")[:2000]