@auscera/socialscrape 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +111 -2
  2. package/bin/socialscrape.mjs +115 -0
  3. package/engine/README.md +243 -0
  4. package/engine/SKILL.md +194 -0
  5. package/engine/agent.py +665 -0
  6. package/engine/batch_manager.py +622 -0
  7. package/engine/cli.py +23 -0
  8. package/engine/handlers.py +1109 -0
  9. package/engine/plugins/__init__.py +77 -0
  10. package/engine/plugins/instagram-scrape/README.md +164 -0
  11. package/engine/plugins/instagram-scrape/SKILL.md +53 -0
  12. package/engine/plugins/instagram-scrape/cli.py +176 -0
  13. package/engine/plugins/instagram-scrape/core.py +408 -0
  14. package/engine/plugins/instagram-scrape/plugin.json +42 -0
  15. package/engine/plugins/linkedin-scrape/README.md +143 -0
  16. package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
  17. package/engine/plugins/linkedin-scrape/cli.py +126 -0
  18. package/engine/plugins/linkedin-scrape/core.py +188 -0
  19. package/engine/plugins/linkedin-scrape/plugin.json +36 -0
  20. package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
  21. package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
  22. package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
  23. package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
  24. package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
  25. package/engine/plugins/pinterest-scraper/README.md +150 -0
  26. package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
  27. package/engine/plugins/pinterest-scraper/cli.py +193 -0
  28. package/engine/plugins/pinterest-scraper/core.py +420 -0
  29. package/engine/plugins/pinterest-scraper/plugin.json +40 -0
  30. package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
  31. package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
  32. package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
  33. package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
  34. package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
  35. package/engine/plugins/shared/__init__.py +15 -0
  36. package/engine/plugins/shared/paths.py +90 -0
  37. package/engine/plugins/shared/process_runner.py +169 -0
  38. package/engine/plugins/shared/session_manager.py +287 -0
  39. package/engine/plugins/threads-scraper/README.md +139 -0
  40. package/engine/plugins/threads-scraper/SKILL.md +43 -0
  41. package/engine/plugins/threads-scraper/cli.py +178 -0
  42. package/engine/plugins/threads-scraper/core.py +460 -0
  43. package/engine/plugins/threads-scraper/plugin.json +40 -0
  44. package/engine/plugins/tiktok-scrape/README.md +158 -0
  45. package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
  46. package/engine/plugins/tiktok-scrape/cli.py +163 -0
  47. package/engine/plugins/tiktok-scrape/core.py +313 -0
  48. package/engine/plugins/tiktok-scrape/plugin.json +40 -0
  49. package/engine/plugins/twitter-scrape/README.md +158 -0
  50. package/engine/plugins/twitter-scrape/SKILL.md +50 -0
  51. package/engine/plugins/twitter-scrape/cli.py +153 -0
  52. package/engine/plugins/twitter-scrape/core.py +254 -0
  53. package/engine/plugins/twitter-scrape/plugin.json +40 -0
  54. package/engine/plugins/youtube-scrape/README.md +199 -0
  55. package/engine/plugins/youtube-scrape/SKILL.md +115 -0
  56. package/engine/plugins/youtube-scrape/cli.py +340 -0
  57. package/engine/plugins/youtube-scrape/core.py +829 -0
  58. package/engine/plugins/youtube-scrape/plugin.json +48 -0
  59. package/engine/requirements.txt +8 -0
  60. package/engine/socialscrape_cli.py +500 -0
  61. package/engine/storage.py +570 -0
  62. package/engine/ui.py +690 -0
  63. package/package.json +27 -3
@@ -0,0 +1,570 @@
1
+ """
2
+ SocialScrape Storage & Path Resolution Engine (`storage.py`).
3
+ Handles dual-mode path resolution (Global OS-native platformdirs vs Local Developer CWD)
4
+ and directory bootstrapping.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import sysconfig
10
+ import json
11
+ import shutil
12
+ import types
13
+ import logging
14
+ import importlib
15
+ import importlib.util
16
+ from abc import ABC, abstractmethod
17
+ from pathlib import Path
18
+ from typing import Dict, Any, Optional, List, Callable
19
+ from platformdirs import user_data_dir, user_config_dir
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ DEFAULT_CONFIG: Dict[str, Any] = {
24
+ "default_quality": "1080p",
25
+ "default_output_format": "mp4",
26
+ "openrouter_model": "cohere/north-mini-code:free",
27
+ "agent_mode_default": True,
28
+ "alternate_screen_buffer": False,
29
+ }
30
+
31
+ PLUGIN_MAP: Dict[str, str] = {
32
+ "youtube": "youtube-scrape",
33
+ "instagram": "instagram-scrape",
34
+ "tiktok": "tiktok-scrape",
35
+ "linkedin": "linkedin-scrape",
36
+ "twitter": "twitter-scrape",
37
+ "reddit": "reddit-discussion-scraper",
38
+ "threads": "threads-scraper",
39
+ "pinterest": "pinterest-scraper",
40
+ "meta": "meta-ad-library-scraper",
41
+ }
42
+
43
+ _FOLDER_TO_PLATFORM: Dict[str, str] = {folder.lower(): plat for plat, folder in PLUGIN_MAP.items()}
44
+
45
+
46
+ def resolve_platform_key(platform_or_folder: str) -> str:
47
+ """Normalizes a plugin folder name or alias to its canonical platform key."""
48
+ clean = platform_or_folder.strip().lower().lstrip("/")
49
+ if clean in PLUGIN_MAP:
50
+ return clean
51
+ return _FOLDER_TO_PLATFORM.get(clean, clean)
52
+
53
+
54
+
55
+ def is_local_mode() -> bool:
56
+ """Check if running in local developer mode."""
57
+ return os.environ.get("SOCIALSCRAPE_LOCAL_MODE") == "1"
58
+
59
+
60
+ def get_data_dir() -> Path:
61
+ """Returns the application data directory (for outputs, chats, myfiles)."""
62
+ if is_local_mode():
63
+ return Path(__file__).parent.resolve()
64
+ return Path(user_data_dir("socialscrape", "socialscrape"))
65
+
66
+
67
+ def get_config_dir() -> Path:
68
+ """Returns the application config directory (for config.json, .env)."""
69
+ if is_local_mode():
70
+ return Path(__file__).parent.resolve()
71
+ return Path(user_config_dir("socialscrape", "socialscrape"))
72
+
73
+
74
+ def get_root_dir() -> Path:
75
+ """Returns the active root data directory based on execution mode."""
76
+ return get_data_dir()
77
+
78
+
79
+ def get_package_dir() -> Path:
80
+ """Returns the package installation root directory containing source code."""
81
+ return Path(__file__).parent.resolve()
82
+
83
+
84
+ def get_bundled_doc_path(filename: str, include_user_data: bool = True) -> Optional[Path]:
85
+ """Resolves bundled root docs (SKILL.md / README.md) across local, editable, and wheel installs."""
86
+ candidates: List[Path] = [
87
+ get_package_dir() / filename,
88
+ Path(sysconfig.get_path("data")) / "share" / "socialscrape" / filename,
89
+ Path(sys.prefix) / "share" / "socialscrape" / filename,
90
+ ]
91
+ if include_user_data:
92
+ candidates.append(get_data_dir() / filename)
93
+
94
+ for path in candidates:
95
+ if path.exists():
96
+ return path
97
+ return None
98
+
99
+
100
+ def get_plugins_dir() -> Path:
101
+ """Returns the plugins directory (bundled inside the package)."""
102
+ return Path(__file__).parent.resolve() / "plugins"
103
+
104
+
105
+ def get_outputs_dir(platform: str) -> Path:
106
+ """Returns the namespaced Outputs directory for a specific platform."""
107
+ platform_key = resolve_platform_key(platform)
108
+ if is_local_mode():
109
+ folder_name = PLUGIN_MAP.get(platform_key, platform)
110
+ return get_plugins_dir() / folder_name / "Outputs"
111
+ return get_data_dir() / "Outputs" / platform_key
112
+
113
+
114
+ def get_state_dir() -> Path:
115
+ """Returns the writable state directory for plugin sessions and rate limits."""
116
+ if is_local_mode():
117
+ return get_plugins_dir() / "shared"
118
+ return get_data_dir() / "state"
119
+
120
+
121
+ def get_chats_dir() -> Path:
122
+ """Returns the session history directory."""
123
+ return get_data_dir() / "chats"
124
+
125
+
126
+ def get_myfiles_dir() -> Path:
127
+ """Returns the user's personal workspace directory."""
128
+ return get_data_dir() / "myfiles"
129
+
130
+
131
+ def get_skills_dir() -> Path:
132
+ """Returns the agent skills directory (for global or local spoke skills)."""
133
+ return get_data_dir() / "skills"
134
+
135
+
136
+ def get_env_file() -> Path:
137
+ """Returns the .env configuration file path."""
138
+ return get_config_dir() / ".env"
139
+
140
+
141
+ def get_config_path() -> Path:
142
+ """Returns the path to the global config file."""
143
+ return get_config_dir() / "config.json"
144
+
145
+
146
+ def load_config() -> Dict[str, Any]:
147
+ """Loads configuration settings from config.json."""
148
+ config_file = get_config_path()
149
+ if config_file.exists():
150
+ try:
151
+ with open(config_file, "r", encoding="utf-8") as f:
152
+ data = json.load(f)
153
+ # Merge with defaults in case new keys were added
154
+ merged = DEFAULT_CONFIG.copy()
155
+ merged.update(data)
156
+ return merged
157
+ except (json.JSONDecodeError, IOError, OSError, PermissionError):
158
+ return DEFAULT_CONFIG.copy()
159
+ return DEFAULT_CONFIG.copy()
160
+
161
+
162
+ def save_config(config_data: Dict[str, Any]) -> None:
163
+ """Saves configuration settings to config.json."""
164
+ config_file = get_config_path()
165
+ config_file.parent.mkdir(parents=True, exist_ok=True)
166
+ with open(config_file, "w", encoding="utf-8") as f:
167
+ json.dump(config_data, f, indent=4)
168
+
169
+
170
+ def bootstrap_global_storage() -> None:
171
+ """
172
+ Ensures storage directories and config files exist.
173
+ Handles migration from legacy ~/.socialscrape/ to OS-native platformdirs,
174
+ or verifies local paths in dev mode.
175
+ """
176
+ if not is_local_mode():
177
+ legacy_dir = Path.home() / ".socialscrape"
178
+ data_dir = get_data_dir()
179
+ config_dir = get_config_dir()
180
+
181
+ # Migrate legacy ~/.socialscrape if present and new directory doesn't exist yet
182
+ if legacy_dir.exists() and legacy_dir.is_dir() and not data_dir.exists():
183
+ try:
184
+ data_dir.parent.mkdir(parents=True, exist_ok=True)
185
+ shutil.move(str(legacy_dir), str(data_dir))
186
+
187
+ # If config dir is separate, migrate config files
188
+ if config_dir != data_dir:
189
+ config_dir.mkdir(parents=True, exist_ok=True)
190
+ for cfg_name in ["config.json", ".env"]:
191
+ src = data_dir / cfg_name
192
+ dst = config_dir / cfg_name
193
+ if src.exists() and not dst.exists():
194
+ shutil.move(str(src), str(dst))
195
+
196
+ try:
197
+ from rich.console import Console
198
+ Console().print(f"[bold green]✓ Successfully migrated legacy storage from ~/.socialscrape to {data_dir}[/bold green]")
199
+ except Exception:
200
+ print(f"[SocialScrape] Successfully migrated legacy storage to {data_dir}")
201
+ except Exception as e:
202
+ try:
203
+ from rich.console import Console
204
+ Console().print(f"[bold yellow]⚠️ Storage migration notice:[/bold yellow] Could not auto-migrate ~/.socialscrape: {e}")
205
+ except Exception:
206
+ print(f"[SocialScrape] Storage migration notice: {e}")
207
+
208
+ data_dir = get_data_dir()
209
+ config_dir = get_config_dir()
210
+ chats = get_chats_dir()
211
+ myfiles = get_myfiles_dir()
212
+ config_path = get_config_path()
213
+ env_path = get_env_file()
214
+
215
+ # Create directories
216
+ data_dir.mkdir(parents=True, exist_ok=True)
217
+ config_dir.mkdir(parents=True, exist_ok=True)
218
+ chats.mkdir(parents=True, exist_ok=True)
219
+ myfiles.mkdir(parents=True, exist_ok=True)
220
+
221
+ # In global mode, build namespaced platform output folders
222
+ if not is_local_mode():
223
+ platform_subdirs = {
224
+ "youtube": ["videos", "thumbnails", "comments", "text_posts"],
225
+ "instagram": ["videos", "thumbnails", "comments", "text_posts"],
226
+ "tiktok": ["videos", "thumbnails", "comments", "text_posts"],
227
+ "linkedin": ["text_posts"],
228
+ "twitter": ["videos", "thumbnails", "comments", "text_posts"],
229
+ "reddit": ["thumbnails", "comments", "text_posts"],
230
+ "threads": ["videos", "thumbnails", "comments", "text_posts"],
231
+ "pinterest": ["videos", "thumbnails", "text_posts"],
232
+ "meta": ["videos", "thumbnails", "text_posts"],
233
+ }
234
+ for plat, subfolders in platform_subdirs.items():
235
+ plat_dir = get_outputs_dir(plat)
236
+ plat_dir.mkdir(parents=True, exist_ok=True)
237
+ for sub in subfolders:
238
+ (plat_dir / sub).mkdir(parents=True, exist_ok=True)
239
+
240
+ # Materialize Root SKILL.md and Spoke skills into global user storage
241
+ pkg_skill = get_bundled_doc_path("SKILL.md", include_user_data=False)
242
+ dest_skill = data_dir / "SKILL.md"
243
+ if pkg_skill and pkg_skill.resolve() != dest_skill.resolve():
244
+ try:
245
+ shutil.copy2(str(pkg_skill), str(dest_skill))
246
+ except (IOError, OSError, PermissionError):
247
+ pass
248
+
249
+ skills_dir = get_skills_dir()
250
+ skills_dir.mkdir(parents=True, exist_ok=True)
251
+ plugins_dir = get_plugins_dir()
252
+ if plugins_dir.exists():
253
+ for p in plugins_dir.iterdir():
254
+ if p.is_dir() and not p.name.startswith("__"):
255
+ p_skill = p / "SKILL.md"
256
+ if p_skill.exists():
257
+ target_spoke_dir = skills_dir / p.name
258
+ target_spoke_dir.mkdir(parents=True, exist_ok=True)
259
+ try:
260
+ shutil.copy2(str(p_skill), str(target_spoke_dir / "SKILL.md"))
261
+ except (IOError, OSError, PermissionError):
262
+ pass
263
+
264
+ # Initialize default config.json if not present
265
+ if not config_path.exists():
266
+ save_config(DEFAULT_CONFIG)
267
+
268
+ # Initialize empty .env template if not present
269
+ if not env_path.exists():
270
+ try:
271
+ with open(env_path, "w", encoding="utf-8") as f:
272
+ f.write("# SocialScrape Environment Configuration\n")
273
+ f.write("OPENROUTER_API_KEY=\n")
274
+ f.write("OPENROUTER_MODEL=cohere/north-mini-code:free\n")
275
+ except (IOError, OSError, PermissionError) as e:
276
+ try:
277
+ from rich.console import Console
278
+ Console().print(f"[bold yellow]⚠️ Notice: Could not write default .env template to {env_path}: {e}[/bold yellow]")
279
+ except Exception:
280
+ print(f"[SocialScrape Warning] Could not write default .env template to {env_path}: {e}")
281
+
282
+
283
+ # ==============================================================================
284
+ # PLUGIN ARCHITECTURE & COLLISION-FREE DISCOVERY
285
+ # ==============================================================================
286
+
287
+ class PluginBase(ABC):
288
+ """Abstract base class that all SocialScrape plugins implement."""
289
+
290
+ @property
291
+ @abstractmethod
292
+ def name(self) -> str:
293
+ """Unique identifier name for the plugin (e.g. 'youtube-scrape')."""
294
+ pass
295
+
296
+ @property
297
+ @abstractmethod
298
+ def display_name(self) -> str:
299
+ """Human-readable name for UI presentation."""
300
+ pass
301
+
302
+ @property
303
+ @abstractmethod
304
+ def description(self) -> str:
305
+ """Short description of what the plugin does."""
306
+ pass
307
+
308
+ @property
309
+ def version(self) -> str:
310
+ """Semantic version string."""
311
+ return "1.0.0"
312
+
313
+ def register_commands(self, router: Any) -> None:
314
+ """Allows plugin to register custom slash commands to the CLI router."""
315
+ pass
316
+
317
+
318
+ class SocialScrapeSpokePlugin(PluginBase):
319
+ """Adapter class wrapping a spoke plugin directory and its plugin.json manifest."""
320
+
321
+ def __init__(self, folder: Path, metadata: Dict[str, Any]):
322
+ self._folder = folder
323
+ self._meta = metadata
324
+ self._name = metadata.get("name", folder.name)
325
+ self._display_name = metadata.get("display_name", folder.name.replace("-", " ").title())
326
+ self._description = metadata.get("description", "")
327
+ self._version = metadata.get("version", "1.0.0")
328
+ self._command = metadata.get("command", f"/{self._name}")
329
+ self._command_desc = metadata.get("command_description", self._description)
330
+ self._aliases = metadata.get("aliases", [])
331
+ self._cli_aliases = metadata.get("cli_aliases", [])
332
+ self._url_patterns = metadata.get("url_patterns", [])
333
+ self._tool_schema = metadata.get("tool_schema", {})
334
+ self._flag_mapping = metadata.get("flag_mapping", {})
335
+
336
+ @property
337
+ def name(self) -> str:
338
+ return self._name
339
+
340
+ @property
341
+ def display_name(self) -> str:
342
+ return self._display_name
343
+
344
+ @property
345
+ def description(self) -> str:
346
+ return self._description
347
+
348
+ @property
349
+ def version(self) -> str:
350
+ return self._version
351
+
352
+ @property
353
+ def command(self) -> str:
354
+ return self._command
355
+
356
+ @property
357
+ def aliases(self) -> List[str]:
358
+ return self._aliases
359
+
360
+ @property
361
+ def cli_aliases(self) -> List[str]:
362
+ return self._cli_aliases
363
+
364
+ @property
365
+ def url_patterns(self) -> List[str]:
366
+ return self._url_patterns
367
+
368
+ @property
369
+ def tool_schema(self) -> Dict[str, Any]:
370
+ return self._tool_schema
371
+
372
+ @property
373
+ def flag_mapping(self) -> Dict[str, Any]:
374
+ return self._flag_mapping
375
+
376
+ @property
377
+ def path(self) -> Path:
378
+ return self._folder
379
+
380
+ @property
381
+ def cli_path(self) -> Optional[Path]:
382
+ cli_file = self._folder / "cli.py"
383
+ return cli_file if cli_file.exists() else None
384
+
385
+ def register_commands(self, router: Any) -> None:
386
+ """Registers the spoke slash command and any aliases with the router."""
387
+ from handlers import handle_plugin_command
388
+ target_name = self.name
389
+ handler_fn = lambda app=None, url="", args=None, **kw: handle_plugin_command(target_name, args or ([url] if url else []))
390
+
391
+ # Primary canonical slash command (included in dropdown & help)
392
+ router.register(self.command, handler_fn, self._command_desc, is_alias=False)
393
+
394
+ # Silent fallback aliases (execution supported, NEVER shown in dropdowns)
395
+ for alias in self.aliases:
396
+ if alias != self.command:
397
+ router.register(alias, handler_fn, is_alias=True)
398
+
399
+
400
+ class PluginLoader:
401
+ """Discovers and instantiates plugins dynamically from the plugins directory."""
402
+
403
+ @staticmethod
404
+ def discover_plugins() -> Dict[str, PluginBase]:
405
+ """Discovers all plugin modules located under plugins directory without namespace package collisions."""
406
+ found_plugins: Dict[str, PluginBase] = {}
407
+ try:
408
+ plugins_dir = get_plugins_dir()
409
+ if not plugins_dir.exists():
410
+ return found_plugins
411
+
412
+ pkg_dir = str(get_package_dir())
413
+ if pkg_dir not in sys.path:
414
+ sys.path.insert(0, pkg_dir)
415
+
416
+ # Ensure root "plugins" module in sys.modules points to socialscrape's plugins
417
+ if "plugins" not in sys.modules:
418
+ mod_plugins = types.ModuleType("plugins")
419
+ init_plugins = plugins_dir / "__init__.py"
420
+ mod_plugins.__file__ = str(init_plugins) if init_plugins.exists() else None
421
+ mod_plugins.__path__ = [str(plugins_dir)]
422
+ mod_plugins.__package__ = "plugins"
423
+ sys.modules["plugins"] = mod_plugins
424
+ else:
425
+ p_mod = sys.modules["plugins"]
426
+ if hasattr(p_mod, "__path__"):
427
+ current_paths = [str(p) for p in p_mod.__path__]
428
+ if str(plugins_dir) not in current_paths:
429
+ try:
430
+ p_mod.__path__.insert(0, str(plugins_dir))
431
+ except Exception:
432
+ p_mod.__path__ = [str(plugins_dir)] + current_paths
433
+
434
+ for folder in sorted(plugins_dir.iterdir()):
435
+ if not folder.is_dir() or folder.name.startswith((".", "_")) or folder.name == "shared":
436
+ continue
437
+
438
+ norm_name = folder.name.replace("-", "_")
439
+ init_file = folder / "__init__.py"
440
+ core_file = folder / "core.py"
441
+ plugin_json_file = folder / "plugin.json"
442
+
443
+ # 1. Register and load plugin package module
444
+ for pkg_name in [f"plugins.{folder.name}", f"plugins.{norm_name}"]:
445
+ if pkg_name not in sys.modules:
446
+ if init_file.exists():
447
+ pkg_spec = importlib.util.spec_from_file_location(
448
+ pkg_name,
449
+ init_file,
450
+ submodule_search_locations=[str(folder)],
451
+ )
452
+ if pkg_spec and pkg_spec.loader:
453
+ pkg_mod = importlib.util.module_from_spec(pkg_spec)
454
+ pkg_mod.__path__ = [str(folder)]
455
+ pkg_mod.__package__ = pkg_name
456
+ sys.modules[pkg_name] = pkg_mod
457
+ try:
458
+ pkg_spec.loader.exec_module(pkg_mod)
459
+ except Exception as exc:
460
+ logger.debug(f"Init execution note for {folder.name}: {exc}")
461
+ else:
462
+ pkg_mod = types.ModuleType(pkg_name)
463
+ pkg_mod.__path__ = [str(folder)]
464
+ pkg_mod.__package__ = pkg_name
465
+ sys.modules[pkg_name] = pkg_mod
466
+ else:
467
+ pkg_mod = types.ModuleType(pkg_name)
468
+ pkg_mod.__path__ = [str(folder)]
469
+ pkg_mod.__package__ = pkg_name
470
+ sys.modules[pkg_name] = pkg_mod
471
+
472
+ if "plugins" in sys.modules:
473
+ setattr(sys.modules["plugins"], folder.name, pkg_mod)
474
+ setattr(sys.modules["plugins"], norm_name, pkg_mod)
475
+
476
+ # 2. Register and load core module if present
477
+ core_mod = None
478
+ if core_file.exists():
479
+ for core_name in [f"plugins.{norm_name}.core", f"plugins.{folder.name}.core"]:
480
+ if core_name in sys.modules:
481
+ core_mod = sys.modules[core_name]
482
+ break
483
+ if not core_mod:
484
+ core_spec = importlib.util.spec_from_file_location(
485
+ f"plugins.{norm_name}.core",
486
+ core_file,
487
+ )
488
+ if core_spec and core_spec.loader:
489
+ core_mod = importlib.util.module_from_spec(core_spec)
490
+ core_mod.__package__ = f"plugins.{norm_name}"
491
+ sys.modules[f"plugins.{norm_name}.core"] = core_mod
492
+ sys.modules[f"plugins.{folder.name}.core"] = core_mod
493
+ for p_name in [f"plugins.{norm_name}", f"plugins.{folder.name}"]:
494
+ if p_name in sys.modules:
495
+ setattr(sys.modules[p_name], "core", core_mod)
496
+ try:
497
+ core_spec.loader.exec_module(core_mod)
498
+ except Exception as exc:
499
+ logger.debug(f"Core execution note for {folder.name}: {exc}")
500
+
501
+ # 3. Read metadata from plugin.json if present
502
+ metadata: Dict[str, Any] = {
503
+ "name": folder.name,
504
+ "path": str(folder),
505
+ "cli": str(folder / "cli.py") if (folder / "cli.py").exists() else None,
506
+ }
507
+ if plugin_json_file.exists():
508
+ try:
509
+ with open(plugin_json_file, "r", encoding="utf-8") as f:
510
+ meta = json.load(f)
511
+ metadata.update(meta)
512
+ except Exception as exc:
513
+ logger.debug(f"JSON read error for {folder.name}: {exc}")
514
+
515
+ # 4. Resolve PluginBase subclass or wrap in SocialScrapeSpokePlugin
516
+ plugin_cls = getattr(core_mod, "__plugin_class__", None) if core_mod else None
517
+ if not plugin_cls and core_mod:
518
+ for attr_name in dir(core_mod):
519
+ attr = getattr(core_mod, attr_name)
520
+ if isinstance(attr, type) and issubclass(attr, PluginBase) and attr is not PluginBase:
521
+ plugin_cls = attr
522
+ break
523
+
524
+ if plugin_cls and issubclass(plugin_cls, PluginBase):
525
+ try:
526
+ instance = plugin_cls()
527
+ found_plugins[instance.name] = instance
528
+ except Exception as exc:
529
+ logger.error(f"Error instantiating plugin from {folder.name}: {exc}")
530
+ else:
531
+ instance = SocialScrapeSpokePlugin(folder, metadata)
532
+ found_plugins[instance.name] = instance
533
+
534
+ except Exception as e:
535
+ logger.error(f"Failed to discover plugins: {e}")
536
+
537
+ return found_plugins
538
+
539
+
540
+ class PluginRegistry:
541
+ """Manages active plugins and lifecycle."""
542
+
543
+ def __init__(self):
544
+ self._plugins: Dict[str, PluginBase] = {}
545
+ self._initialized = False
546
+
547
+ def initialize(self) -> None:
548
+ """Discovers and registers all available plugins."""
549
+ if not self._initialized:
550
+ self._plugins = PluginLoader.discover_plugins()
551
+ self._initialized = True
552
+
553
+ def get_plugin(self, name: str) -> Optional[PluginBase]:
554
+ """Returns a registered plugin by name."""
555
+ self.initialize()
556
+ return self._plugins.get(name)
557
+
558
+ def list_plugins(self) -> List[PluginBase]:
559
+ """Returns all registered plugin instances."""
560
+ self.initialize()
561
+ return list(self._plugins.values())
562
+
563
+ def register(self, plugin: PluginBase) -> None:
564
+ """Manually registers a plugin instance."""
565
+ self._plugins[plugin.name] = plugin
566
+
567
+
568
+ plugin_registry = PluginRegistry()
569
+
570
+