@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,665 @@
1
+ """
2
+ SocialScrape AI Agent & OpenRouter Core Engine (`agent.py`).
3
+ Handles OpenRouter LLM orchestration, stateless tool schema definitions,
4
+ session memory persistence, and dynamic O(1) dictionary tool dispatching.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import time
10
+ import json
11
+ from pathlib import Path
12
+ from typing import List, Dict, Any, Optional, Callable, Tuple
13
+
14
+ import requests
15
+ import dotenv
16
+
17
+ from prompt_toolkit import prompt
18
+ from prompt_toolkit.formatted_text import HTML
19
+
20
+ from storage import (
21
+ get_root_dir,
22
+ get_plugins_dir,
23
+ get_outputs_dir,
24
+ get_env_file,
25
+ get_chats_dir,
26
+ )
27
+ from ui import (
28
+ console,
29
+ render_action_card,
30
+ render_ai_response,
31
+ render_plugin_features,
32
+ get_active_plugins,
33
+ COLOR_MUTED,
34
+ )
35
+
36
+ ROOT_DIR = get_root_dir()
37
+ PLUGINS_DIR = get_plugins_dir()
38
+ ENV_FILE = get_env_file()
39
+ CHATS_DIR = get_chats_dir()
40
+
41
+ # Auto-load environment variables from .env if present
42
+ if ENV_FILE.exists():
43
+ dotenv.load_dotenv(ENV_FILE)
44
+
45
+ DEFAULT_OPENROUTER_MODEL = "cohere/north-mini-code:free"
46
+
47
+ ALLOWED_OPENROUTER_MODELS = [
48
+ {
49
+ "id": "cohere/north-mini-code:free",
50
+ "name": "North Mini Code (free)",
51
+ "provider": "OpenRouter",
52
+ "is_free": True,
53
+ "context_length": 256000,
54
+ "description": "Cohere agentic coding model, optimized for tool use and structured scraping.",
55
+ },
56
+ {
57
+ "id": "z-ai/glm-5.2:free",
58
+ "name": "GLM 5.2 (free)",
59
+ "provider": "OpenRouter",
60
+ "is_free": True,
61
+ "context_length": 128000,
62
+ "description": "Z-AI GLM 5.2 high capability general and reasoning model.",
63
+ },
64
+ {
65
+ "id": "minimax/minimax-m3:free",
66
+ "name": "MiniMax-M3 Free",
67
+ "provider": "OpenRouter",
68
+ "is_free": True,
69
+ "context_length": 1000000,
70
+ "description": "MiniMax-M3 1M token context window model.",
71
+ },
72
+ {
73
+ "id": "minimax/minimax-m2.7:free",
74
+ "name": "MiniMax-M2.7 (free)",
75
+ "provider": "OpenRouter",
76
+ "is_free": True,
77
+ "context_length": 256000,
78
+ "description": "MiniMax-M2.7 fast reasoning model.",
79
+ },
80
+ {
81
+ "id": "poolside/laguna-xs-2.1:free",
82
+ "name": "Laguna XS 2.1 (free)",
83
+ "provider": "OpenRouter",
84
+ "is_free": True,
85
+ "context_length": 64000,
86
+ "description": "Poolside Laguna XS 2.1 ultra-fast coding and execution model.",
87
+ },
88
+ {
89
+ "id": "poolside/laguna-s-2.1:free",
90
+ "name": "Laguna S 2.1 (free)",
91
+ "provider": "OpenRouter",
92
+ "is_free": True,
93
+ "context_length": 128000,
94
+ "description": "Poolside Laguna S 2.1 balanced speed and intelligence model.",
95
+ },
96
+ {
97
+ "id": "nvidia/nemotron-3-ultra-550b-a55b:free",
98
+ "name": "Nemotron 3 Ultra 550B (free)",
99
+ "provider": "OpenRouter",
100
+ "is_free": True,
101
+ "context_length": 128000,
102
+ "description": "NVIDIA Nemotron 3 Ultra 550B flagship foundation model.",
103
+ },
104
+ {
105
+ "id": "nvidia/nemotron-3-super-120b-a12b:free",
106
+ "name": "Nemotron 3 Super 120B (free)",
107
+ "provider": "OpenRouter",
108
+ "is_free": True,
109
+ "context_length": 128000,
110
+ "description": "NVIDIA Nemotron 3 Super 120B high efficiency reasoning model.",
111
+ },
112
+ ]
113
+
114
+ # ==============================================================================
115
+ # 1. API KEY & MODEL CONFIGURATION HELPERS
116
+ # ==============================================================================
117
+
118
+ def get_openrouter_api_key(prompt_if_missing: bool = False) -> Optional[str]:
119
+ """
120
+ Discovers OPENROUTER_API_KEY from environment variables or .env file.
121
+ If missing and prompt_if_missing is True, gracefully prompts the user and saves to .env.
122
+ """
123
+ api_key = os.environ.get("OPENROUTER_API_KEY", "").strip()
124
+ if api_key:
125
+ return api_key
126
+
127
+ if prompt_if_missing:
128
+ console.print("[bold yellow]🔑 OpenRouter API Key required for Agent mode.[/bold yellow]")
129
+ console.print("[dim]Get your free key at https://openrouter.ai/keys[/dim]")
130
+ try:
131
+ entered_key = prompt(
132
+ HTML("<b><style color='#fab283'>Enter OPENROUTER_API_KEY: </style></b>"),
133
+ is_password=True,
134
+ ).strip()
135
+ if entered_key:
136
+ save_openrouter_api_key(entered_key)
137
+ return entered_key
138
+ except (KeyboardInterrupt, EOFError):
139
+ pass
140
+ return None
141
+
142
+
143
+ def save_openrouter_api_key(key: str) -> None:
144
+ """Saves the OpenRouter API key to memory and persists to .env file."""
145
+ os.environ["OPENROUTER_API_KEY"] = key
146
+ if not ENV_FILE.exists():
147
+ ENV_FILE.touch()
148
+ dotenv.set_key(str(ENV_FILE), "OPENROUTER_API_KEY", key)
149
+ console.print("[bold green]✅ OpenRouter API key saved to .env securely.[/bold green]")
150
+
151
+
152
+ def get_openrouter_model() -> str:
153
+ """Retrieves configured default model from allowed list."""
154
+ current = os.environ.get("OPENROUTER_MODEL", "").strip()
155
+ valid_ids = [m["id"] for m in ALLOWED_OPENROUTER_MODELS]
156
+ if current in valid_ids:
157
+ return current
158
+ return DEFAULT_OPENROUTER_MODEL
159
+
160
+
161
+ def save_openrouter_model(model_name: str) -> None:
162
+ """Persists chosen model to environment and .env file."""
163
+ os.environ["OPENROUTER_MODEL"] = model_name
164
+ if not ENV_FILE.exists():
165
+ ENV_FILE.touch()
166
+ dotenv.set_key(str(ENV_FILE), "OPENROUTER_MODEL", model_name)
167
+
168
+
169
+ def fetch_openrouter_models(force_refresh: bool = False) -> List[Dict[str, Any]]:
170
+ """Returns the strict curated list of free OpenRouter models."""
171
+ return ALLOWED_OPENROUTER_MODELS
172
+
173
+
174
+ # ==============================================================================
175
+ # 2. SESSION MEMORY & CONVERSATION PERSISTENCE
176
+ # ==============================================================================
177
+
178
+ CURRENT_SESSION_ID: str = time.strftime("session_%Y%m%d_%H%M%S")
179
+ CONVERSATION_HISTORY: List[Dict[str, Any]] = []
180
+
181
+
182
+ def init_new_chat_session() -> str:
183
+ """Initializes a new chat session and resets in-memory conversation history."""
184
+ global CURRENT_SESSION_ID, CONVERSATION_HISTORY
185
+ CURRENT_SESSION_ID = time.strftime("session_%Y%m%d_%H%M%S")
186
+ CONVERSATION_HISTORY = []
187
+ CHATS_DIR.mkdir(parents=True, exist_ok=True)
188
+ return CURRENT_SESSION_ID
189
+
190
+
191
+ def save_chat_session() -> None:
192
+ """Persists current session messages to chats/<session_id>.json."""
193
+ try:
194
+ CHATS_DIR.mkdir(parents=True, exist_ok=True)
195
+ session_file = CHATS_DIR / f"{CURRENT_SESSION_ID}.json"
196
+
197
+ # Derive title from first user query
198
+ title = "Empty Session"
199
+ for m in CONVERSATION_HISTORY:
200
+ if m.get("role") == "user" and not m.get("content", "").startswith("[System Observation"):
201
+ raw = m.get("content", "").strip()
202
+ title = (raw[:50] + "...") if len(raw) > 50 else raw
203
+ break
204
+
205
+ data = {
206
+ "session_id": CURRENT_SESSION_ID,
207
+ "title": title,
208
+ "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
209
+ "active_model": get_openrouter_model(),
210
+ "messages": CONVERSATION_HISTORY
211
+ }
212
+ with open(session_file, "w", encoding="utf-8") as f:
213
+ json.dump(data, f, indent=2, ensure_ascii=False)
214
+ except (IOError, OSError, PermissionError) as e:
215
+ render_action_card(f"[dim red]Warning: Could not persist session to disk: {e}[/dim red]")
216
+
217
+
218
+ def get_current_session_id() -> str:
219
+ """Returns current active session ID."""
220
+ return CURRENT_SESSION_ID
221
+
222
+
223
+ def set_current_session_id(session_id: str) -> None:
224
+ """Sets active session ID."""
225
+ global CURRENT_SESSION_ID
226
+ CURRENT_SESSION_ID = session_id
227
+
228
+
229
+ def get_conversation_history() -> List[Dict[str, Any]]:
230
+ """Returns current in-memory conversation history."""
231
+ return CONVERSATION_HISTORY
232
+
233
+
234
+ def set_conversation_history(history: List[Dict[str, Any]]) -> None:
235
+ """Sets current in-memory conversation history."""
236
+ global CONVERSATION_HISTORY
237
+ CONVERSATION_HISTORY = history
238
+
239
+
240
+ # ==============================================================================
241
+ # 3. STATELESS OPENROUTER CORE & DYNAMIC TOOL REGISTRY
242
+ # ==============================================================================
243
+
244
+ CORE_HUB_TOOLS: List[Dict[str, Any]] = [
245
+ {
246
+ "type": "function",
247
+ "function": {
248
+ "name": "batch_scrape",
249
+ "description": "Performs bulk batch scraping of multiple URLs or targets from a .txt, .csv, or .md file with rate-limiting and human-like jitter delays.",
250
+ "parameters": {
251
+ "type": "object",
252
+ "properties": {
253
+ "platform": {
254
+ "type": "string",
255
+ "description": "Target platform / scraper plugin."
256
+ },
257
+ "input_file": {
258
+ "type": "string",
259
+ "description": "Path to the .txt, .csv, or .md file containing targets."
260
+ },
261
+ "download_video": {"type": "boolean"},
262
+ "download_thumbnail": {"type": "boolean"},
263
+ "quality": {"type": "string", "enum": ["360p", "480p", "720p", "1080p", "best"]},
264
+ "extract_all": {"type": "boolean"}
265
+ },
266
+ "required": ["platform", "input_file"]
267
+ }
268
+ }
269
+ },
270
+ {
271
+ "type": "function",
272
+ "function": {
273
+ "name": "resume_batch",
274
+ "description": "Resumes an interrupted or incomplete bulk batch scrape from its saved JSON checkpoint file in batches/.",
275
+ "parameters": {
276
+ "type": "object",
277
+ "properties": {
278
+ "batch_id": {
279
+ "type": "string",
280
+ "description": "Optional specific batch ID to resume (e.g. 'batch_20260831_183000'). If omitted, prompts with active incomplete batches."
281
+ }
282
+ }
283
+ }
284
+ }
285
+ },
286
+ {
287
+ "type": "function",
288
+ "function": {
289
+ "name": "list_plugins",
290
+ "description": "Lists all active SocialScrape social scraper plugins and their health statuses.",
291
+ "parameters": {"type": "object", "properties": {}}
292
+ }
293
+ },
294
+ {
295
+ "type": "function",
296
+ "function": {
297
+ "name": "view_features",
298
+ "description": "Displays the complete feature matrix of SocialScrape plugins.",
299
+ "parameters": {
300
+ "type": "object",
301
+ "properties": {
302
+ "plugin_name": {"type": "string", "description": "Optional plugin name."}
303
+ }
304
+ }
305
+ }
306
+ },
307
+ {
308
+ "type": "function",
309
+ "function": {
310
+ "name": "view_outputs",
311
+ "description": "Displays the tree viewer of all downloaded media, transcripts, and metadata files in the Outputs folder.",
312
+ "parameters": {"type": "object", "properties": {}}
313
+ }
314
+ },
315
+ {
316
+ "type": "function",
317
+ "function": {
318
+ "name": "switch_model",
319
+ "description": "Switches the active OpenRouter AI LLM model to a new model ID.",
320
+ "parameters": {
321
+ "type": "object",
322
+ "properties": {
323
+ "model_id": {"type": "string", "description": "Target OpenRouter model ID."}
324
+ },
325
+ "required": ["model_id"]
326
+ }
327
+ }
328
+ }
329
+ ]
330
+
331
+ CORE_FLAG_MAP: Dict[str, Dict[str, Any]] = {
332
+ "batch_scrape": {
333
+ "positional": [],
334
+ "flags": {
335
+ "input_file": "--input-file",
336
+ "download_video": "--download-video",
337
+ "download_thumbnail": "--download-thumb",
338
+ "quality": "-q",
339
+ "extract_all": "-a",
340
+ },
341
+ "display_name": "Batch Scraper Engine",
342
+ "handler_key": "batch",
343
+ },
344
+ }
345
+
346
+
347
+ def build_dynamic_tools() -> Tuple[List[Dict[str, Any]], Dict[str, Dict[str, Any]]]:
348
+ """
349
+ Dynamically aggregates tool schemas and parameter flag mappings by
350
+ discovering all active plugins and reading their plugin.json manifests.
351
+ """
352
+ tools = list(CORE_HUB_TOOLS)
353
+ flag_map = dict(CORE_FLAG_MAP)
354
+
355
+ for p in get_active_plugins():
356
+ t_schema = p.get("tool_schema")
357
+ f_map = p.get("flag_mapping")
358
+ p_name = p.get("name", "")
359
+ display_name = p.get("display_name", p_name.replace("-", " ").title())
360
+ cli_alias = p.get("cli_aliases", [p_name])[0] if p.get("cli_aliases") else p_name
361
+
362
+ if t_schema and isinstance(t_schema, dict):
363
+ tools.insert(0, {
364
+ "type": "function",
365
+ "function": t_schema
366
+ })
367
+
368
+ fn_name = t_schema.get("name")
369
+ if fn_name:
370
+ flag_map[fn_name] = {
371
+ "positional": f_map.get("positional", []) if f_map else [],
372
+ "flags": f_map.get("flags", {}) if f_map else {},
373
+ "display_name": display_name,
374
+ "handler_key": cli_alias,
375
+ "plugin_name": p_name,
376
+ }
377
+
378
+ return tools, flag_map
379
+
380
+
381
+ # Dynamically initialized tool and flag registries
382
+ SOCIALSCRAPE_TOOLS, TOOL_PARAM_FLAG_MAP = build_dynamic_tools()
383
+
384
+ # Global handler registry mapping
385
+ TOOL_HANDLERS: Dict[str, Callable[..., Any]] = {}
386
+
387
+
388
+ def register_tool_handlers(handlers: Dict[str, Callable[..., Any]]) -> None:
389
+ """Registers callback functions for CLI commands."""
390
+ global TOOL_HANDLERS
391
+ TOOL_HANDLERS.update(handlers)
392
+
393
+
394
+ def build_cmd_args(fn_name: str, fn_args: Dict[str, Any]) -> List[str]:
395
+ """Dynamically transforms tool JSON arguments into CLI flag tokens."""
396
+ spec = TOOL_PARAM_FLAG_MAP.get(fn_name)
397
+ if not spec:
398
+ return []
399
+
400
+ cmd_args: List[str] = []
401
+
402
+ # 1. Positional arguments
403
+ for pos_key in spec.get("positional", []):
404
+ val = fn_args.get(pos_key)
405
+ if val:
406
+ cmd_args.append(str(val))
407
+
408
+ # 2. Flag arguments
409
+ flag_map = spec.get("flags", {})
410
+ for key, flag in flag_map.items():
411
+ val = fn_args.get(key)
412
+ if val is None or val is False:
413
+ continue
414
+ if isinstance(val, bool) and val is True:
415
+ cmd_args.append(flag)
416
+ else:
417
+ cmd_args.extend([flag, str(val)])
418
+
419
+ return cmd_args
420
+
421
+
422
+ def extract_youtube_observation(fn_args: Dict[str, Any]) -> str:
423
+ """Extracts scraped transcript snippet to feed back into conversation context."""
424
+ result_details = f"Tool 'youtube_scrape' completed successfully for args: {json.dumps(fn_args)}."
425
+ try:
426
+ url_str = fn_args.get("url", "")
427
+ vid_id = None
428
+ if "v=" in url_str:
429
+ vid_id = url_str.split("v=")[-1].split("&")[0]
430
+ elif "youtu.be/" in url_str:
431
+ vid_id = url_str.split("youtu.be/")[-1].split("?")[0]
432
+ elif "shorts/" in url_str:
433
+ vid_id = url_str.split("shorts/")[-1].split("?")[0]
434
+ elif "live/" in url_str:
435
+ vid_id = url_str.split("live/")[-1].split("?")[0]
436
+
437
+ if vid_id:
438
+ yt_out_base = get_outputs_dir("youtube")
439
+ for sub in ("videos", "shorts", "live"):
440
+ t_file = yt_out_base / sub / vid_id / "transcript.json"
441
+ if t_file.exists():
442
+ with open(t_file, "r", encoding="utf-8") as f:
443
+ t_data = json.load(f)
444
+ title = t_data.get("title", vid_id)
445
+ text_snippet = t_data.get("text", "")[:2500]
446
+ result_details = (
447
+ f"Scraped YouTube video: '{title}' (ID: {vid_id}).\n"
448
+ f"Saved to {t_file.parent}/\n\n"
449
+ f"Transcript Content Snippet:\n{text_snippet}"
450
+ )
451
+ break
452
+ except (IOError, OSError, json.JSONDecodeError, KeyError, IndexError):
453
+ pass
454
+ return result_details
455
+
456
+
457
+ def execute_tool_call(
458
+ fn_name: str,
459
+ fn_args: Dict[str, Any],
460
+ handlers: Dict[str, Callable[..., Any]]
461
+ ) -> str:
462
+ """
463
+ Executes a tool call dynamically via O(1) dictionary lookup and returns observation text.
464
+ """
465
+ if fn_name == "batch_scrape":
466
+ platform = fn_args.get("platform", "youtube")
467
+ input_file = fn_args.get("input_file", "")
468
+ extra_cmd_args = build_cmd_args(fn_name, fn_args)
469
+
470
+ render_action_card(f"[bold #5c9cf5]Routing to Batch Extraction Engine:[/bold #5c9cf5] [dim]{platform} -> {input_file}[/dim]")
471
+ batch_handler = handlers.get("batch")
472
+ if batch_handler:
473
+ batch_handler([platform, input_file, *extra_cmd_args])
474
+ return f"Batch extraction executed for platform '{platform}' from file '{input_file}'."
475
+
476
+ elif fn_name == "resume_batch":
477
+ batch_id = fn_args.get("batch_id")
478
+ render_action_card(f"[bold #5c9cf5]Action:[/bold #5c9cf5] Resuming batch checkpoint {batch_id or ''}...")
479
+ resume_batch_handler = handlers.get("resume_batch")
480
+ if resume_batch_handler:
481
+ resume_batch_handler([batch_id] if batch_id else [])
482
+ return f"Batch checkpoint resumption executed for {batch_id or 'latest'}."
483
+
484
+ elif fn_name in TOOL_PARAM_FLAG_MAP:
485
+ spec = TOOL_PARAM_FLAG_MAP[fn_name]
486
+ cmd_args = build_cmd_args(fn_name, fn_args)
487
+ arg_display = " ".join(cmd_args) if cmd_args else "interactive"
488
+ render_action_card(f"[bold #5c9cf5]Routing to {spec['display_name']}:[/bold #5c9cf5] [dim]{arg_display}[/dim]")
489
+
490
+ handler = handlers.get(spec["handler_key"])
491
+ if handler:
492
+ handler(cmd_args)
493
+
494
+ if fn_name == "youtube_scrape" and not fn_args.get("input_file"):
495
+ return extract_youtube_observation(fn_args)
496
+ return f"{spec['display_name']} executed successfully for: {json.dumps(fn_args)}."
497
+
498
+ elif fn_name == "list_plugins":
499
+ render_action_card("[bold #5c9cf5]Action:[/bold #5c9cf5] Listing active plugins...")
500
+ plugins_handler = handlers.get("plugins")
501
+ if plugins_handler:
502
+ plugins_handler()
503
+ return "Active plugins listed successfully."
504
+
505
+ elif fn_name == "view_features":
506
+ render_action_card("[bold #5c9cf5]Action:[/bold #5c9cf5] Displaying plugin feature matrix...")
507
+ render_plugin_features(fn_args.get("plugin_name", "youtube-scrape"))
508
+ return "Plugin feature matrix displayed."
509
+
510
+ elif fn_name == "view_outputs":
511
+ render_action_card("[bold #5c9cf5]Action:[/bold #5c9cf5] Browsing scraped outputs...")
512
+ outputs_handler = handlers.get("outputs")
513
+ if outputs_handler:
514
+ outputs_handler()
515
+ return "Outputs directory tree displayed."
516
+
517
+ elif fn_name == "switch_model":
518
+ target_model = fn_args.get("model_id")
519
+ if target_model:
520
+ save_openrouter_model(target_model)
521
+ render_action_card(f"[bold green]Active AI Model switched to: {target_model}[/bold green]")
522
+ return f"Active AI model switched to {target_model}."
523
+ return "No model_id provided for switch_model."
524
+
525
+ return f"Unknown tool '{fn_name}' executed."
526
+
527
+
528
+ # ==============================================================================
529
+ # 5. ORCHESTRATION & AGENT EXECUTION
530
+ # ==============================================================================
531
+
532
+ def run_openrouter_agent(user_query: str, handlers: Optional[Dict[str, Callable[..., Any]]] = None) -> None:
533
+ """
534
+ Stateful AI query router with multi-turn conversation memory and session logging.
535
+ Maintains context across user questions, tool calls, and execution observations.
536
+ """
537
+ global CONVERSATION_HISTORY
538
+ active_handlers = dict(TOOL_HANDLERS)
539
+ if handlers:
540
+ active_handlers.update(handlers)
541
+
542
+ api_key = get_openrouter_api_key(prompt_if_missing=True)
543
+ if not api_key:
544
+ console.print("[bold yellow]⚠️ OpenRouter API key is required to run in Agent mode.[/bold yellow]")
545
+ console.print("[dim]Use /manual to run direct slash commands or /models to select a model.[/dim]")
546
+ return
547
+
548
+ model = get_openrouter_model()
549
+ console.print(f"[dim]🤖 Thinking ({model.split('/')[-1]})...[/dim]")
550
+
551
+ # 1. Record current user query in conversation memory
552
+ CONVERSATION_HISTORY.append({
553
+ "role": "user",
554
+ "content": user_query,
555
+ "timestamp": time.strftime("%I:%M %p")
556
+ })
557
+
558
+ headers = {
559
+ "Authorization": f"Bearer {api_key}",
560
+ "HTTP-Referer": "https://github.com/delightc123/social-scrape",
561
+ "X-Title": "SocialScrape AI Hub",
562
+ "Content-Type": "application/json"
563
+ }
564
+
565
+ system_prompt = (
566
+ "You are SocialScrape AI, an expert social media scraper and media downloader CLI orchestrator. "
567
+ "You maintain active conversation memory throughout the session. Remember all past actions, URLs, and scraped items. "
568
+ "When the user asks follow-up questions (e.g. 'is it done?', 'what was the URL?', 'what did you scrape?'), "
569
+ "reference the previous tool observations and conversation history to answer accurately. "
570
+ "When the user requests scraping, downloading, extracting transcripts, comments, metadata, or channel videos, "
571
+ "invoke the corresponding scraper tool with extracted parameters. "
572
+ "If the user provides an input file or requests bulk scraping, invoke batch_scrape or pass input_file. "
573
+ "If the user asks to resume an interrupted batch, invoke resume_batch. "
574
+ "If the user asks about available features or capabilities, invoke view_features. "
575
+ "Respond concisely and helpfully."
576
+ )
577
+
578
+ # 2. Build multi-turn context payload (last 16 turns)
579
+ api_messages = [{"role": "system", "content": system_prompt}]
580
+ for msg in CONVERSATION_HISTORY[-16:]:
581
+ clean_msg = {"role": msg["role"], "content": msg.get("content", "")}
582
+ if "tool_calls" in msg:
583
+ clean_msg["tool_calls"] = msg["tool_calls"]
584
+ if "tool_call_id" in msg:
585
+ clean_msg["tool_call_id"] = msg["tool_call_id"]
586
+ if "name" in msg:
587
+ clean_msg["name"] = msg["name"]
588
+ api_messages.append(clean_msg)
589
+
590
+ payload = {
591
+ "model": model,
592
+ "messages": api_messages,
593
+ "tools": SOCIALSCRAPE_TOOLS,
594
+ "tool_choice": "auto"
595
+ }
596
+
597
+ try:
598
+ res = requests.post(
599
+ "https://openrouter.ai/api/v1/chat/completions",
600
+ headers=headers,
601
+ json=payload,
602
+ timeout=30
603
+ )
604
+
605
+ if res.status_code == 401:
606
+ console.print("[bold red][!] Unauthorized (401): Invalid OpenRouter API key. Run /agent or update .env.[/bold red]")
607
+ return
608
+ elif res.status_code == 429:
609
+ console.print("[bold yellow]⚠️ OpenRouter rate limit (429). Switch to another model using /models.[/bold yellow]")
610
+ return
611
+ elif res.status_code != 200:
612
+ console.print(f"[bold red][!] OpenRouter Error ({res.status_code}): {res.text}[/bold red]")
613
+ return
614
+
615
+ data = res.json()
616
+ choice = data.get("choices", [{}])[0]
617
+ message = choice.get("message", {})
618
+ tool_calls = message.get("tool_calls", [])
619
+ content = message.get("content", "")
620
+
621
+ if tool_calls:
622
+ CONVERSATION_HISTORY.append({
623
+ "role": "assistant",
624
+ "content": content or "",
625
+ "tool_calls": tool_calls,
626
+ "timestamp": time.strftime("%I:%M %p")
627
+ })
628
+
629
+ # Execute each tool call dynamically
630
+ for call in tool_calls:
631
+ call_id = call.get("id") or f"call_{int(time.time() * 1000)}"
632
+ fn = call.get("function", {})
633
+ fn_name = fn.get("name", "")
634
+ raw_args = fn.get("arguments", "{}")
635
+ try:
636
+ fn_args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
637
+ except (json.JSONDecodeError, TypeError):
638
+ fn_args = {}
639
+
640
+ obs_content = execute_tool_call(fn_name, fn_args, active_handlers)
641
+
642
+ CONVERSATION_HISTORY.append({
643
+ "role": "tool",
644
+ "tool_call_id": call_id,
645
+ "name": fn_name,
646
+ "content": obs_content,
647
+ "timestamp": time.strftime("%I:%M %p")
648
+ })
649
+
650
+ if content:
651
+ render_ai_response(content, model)
652
+ if not tool_calls:
653
+ CONVERSATION_HISTORY.append({
654
+ "role": "assistant",
655
+ "content": content,
656
+ "timestamp": time.strftime("%I:%M %p")
657
+ })
658
+
659
+ # Save complete session transcript to chats/<session_id>.json
660
+ save_chat_session()
661
+
662
+ except requests.exceptions.Timeout:
663
+ render_action_card("[bold red][!] OpenRouter request timed out (30s). Try again or choose a faster model via /models.[/bold red]")
664
+ except Exception as e:
665
+ render_action_card(f"[bold red][!] AI execution error: {e}[/bold red]")