@auscera/socialscrape 0.0.0-stage → 2.0.2
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.
- package/README.md +111 -2
- package/bin/socialscrape.mjs +115 -0
- package/engine/README.md +245 -0
- package/engine/SKILL.md +194 -0
- package/engine/agent.py +665 -0
- package/engine/batch_manager.py +622 -0
- package/engine/cli.py +23 -0
- package/engine/handlers.py +1109 -0
- package/engine/plugins/__init__.py +77 -0
- package/engine/plugins/instagram-scrape/README.md +164 -0
- package/engine/plugins/instagram-scrape/SKILL.md +53 -0
- package/engine/plugins/instagram-scrape/cli.py +176 -0
- package/engine/plugins/instagram-scrape/core.py +408 -0
- package/engine/plugins/instagram-scrape/plugin.json +42 -0
- package/engine/plugins/linkedin-scrape/README.md +143 -0
- package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
- package/engine/plugins/linkedin-scrape/cli.py +126 -0
- package/engine/plugins/linkedin-scrape/core.py +188 -0
- package/engine/plugins/linkedin-scrape/plugin.json +36 -0
- package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
- package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
- package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
- package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
- package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
- package/engine/plugins/pinterest-scraper/README.md +150 -0
- package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
- package/engine/plugins/pinterest-scraper/cli.py +193 -0
- package/engine/plugins/pinterest-scraper/core.py +420 -0
- package/engine/plugins/pinterest-scraper/plugin.json +40 -0
- package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
- package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
- package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
- package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
- package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
- package/engine/plugins/shared/__init__.py +15 -0
- package/engine/plugins/shared/paths.py +90 -0
- package/engine/plugins/shared/process_runner.py +169 -0
- package/engine/plugins/shared/session_manager.py +287 -0
- package/engine/plugins/threads-scraper/README.md +139 -0
- package/engine/plugins/threads-scraper/SKILL.md +43 -0
- package/engine/plugins/threads-scraper/cli.py +178 -0
- package/engine/plugins/threads-scraper/core.py +460 -0
- package/engine/plugins/threads-scraper/plugin.json +40 -0
- package/engine/plugins/tiktok-scrape/README.md +158 -0
- package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
- package/engine/plugins/tiktok-scrape/cli.py +163 -0
- package/engine/plugins/tiktok-scrape/core.py +313 -0
- package/engine/plugins/tiktok-scrape/plugin.json +40 -0
- package/engine/plugins/twitter-scrape/README.md +158 -0
- package/engine/plugins/twitter-scrape/SKILL.md +50 -0
- package/engine/plugins/twitter-scrape/cli.py +153 -0
- package/engine/plugins/twitter-scrape/core.py +254 -0
- package/engine/plugins/twitter-scrape/plugin.json +40 -0
- package/engine/plugins/youtube-scrape/README.md +199 -0
- package/engine/plugins/youtube-scrape/SKILL.md +115 -0
- package/engine/plugins/youtube-scrape/cli.py +340 -0
- package/engine/plugins/youtube-scrape/core.py +829 -0
- package/engine/plugins/youtube-scrape/plugin.json +48 -0
- package/engine/requirements.txt +8 -0
- package/engine/socialscrape_cli.py +500 -0
- package/engine/storage.py +570 -0
- package/engine/ui.py +690 -0
- package/package.json +27 -3
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SocialScrape Command Handlers & Subprocess Execution Engine (`handlers.py`).
|
|
3
|
+
Contains standalone and subprocess execution handlers for all 9 social scrapers,
|
|
4
|
+
batch extraction routing, checkpoint resumption, interactive modals, and session management.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import json
|
|
11
|
+
import subprocess
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import List, Dict, Any, Optional, Tuple, Callable
|
|
14
|
+
|
|
15
|
+
from prompt_toolkit import prompt as pt_prompt
|
|
16
|
+
|
|
17
|
+
from rich.table import Table
|
|
18
|
+
from rich.panel import Panel
|
|
19
|
+
from rich.markdown import Markdown
|
|
20
|
+
from rich.tree import Tree
|
|
21
|
+
|
|
22
|
+
from storage import (
|
|
23
|
+
get_package_dir,
|
|
24
|
+
get_bundled_doc_path,
|
|
25
|
+
get_data_dir,
|
|
26
|
+
get_config_dir,
|
|
27
|
+
get_config_path,
|
|
28
|
+
get_skills_dir,
|
|
29
|
+
get_root_dir,
|
|
30
|
+
get_plugins_dir,
|
|
31
|
+
get_outputs_dir,
|
|
32
|
+
get_state_dir,
|
|
33
|
+
get_chats_dir,
|
|
34
|
+
load_config,
|
|
35
|
+
save_config,
|
|
36
|
+
PLUGIN_MAP,
|
|
37
|
+
plugin_registry,
|
|
38
|
+
is_local_mode,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
from ui import (
|
|
42
|
+
console,
|
|
43
|
+
COLOR_TEXT,
|
|
44
|
+
COLOR_MUTED,
|
|
45
|
+
COLOR_PRIMARY,
|
|
46
|
+
COLOR_ACCENT,
|
|
47
|
+
COLOR_BORDER,
|
|
48
|
+
display_home_screen,
|
|
49
|
+
render_user_message,
|
|
50
|
+
render_ai_response,
|
|
51
|
+
render_action_card,
|
|
52
|
+
render_plugin_features,
|
|
53
|
+
get_active_plugins,
|
|
54
|
+
open_chat_history_viewer,
|
|
55
|
+
render_doctor_report,
|
|
56
|
+
reset_terminal_mouse_mode,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
from agent import (
|
|
60
|
+
ALLOWED_OPENROUTER_MODELS,
|
|
61
|
+
get_openrouter_api_key,
|
|
62
|
+
get_openrouter_model,
|
|
63
|
+
save_openrouter_model,
|
|
64
|
+
init_new_chat_session,
|
|
65
|
+
save_chat_session,
|
|
66
|
+
get_current_session_id,
|
|
67
|
+
set_current_session_id,
|
|
68
|
+
get_conversation_history,
|
|
69
|
+
set_conversation_history,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
from batch_manager import (
|
|
73
|
+
run_batch_extraction,
|
|
74
|
+
resume_batch,
|
|
75
|
+
get_incomplete_batches,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
from plugins.shared.process_runner import run_plugin_subprocess
|
|
79
|
+
|
|
80
|
+
ROOT_DIR = get_root_dir()
|
|
81
|
+
PLUGINS_DIR = get_plugins_dir()
|
|
82
|
+
CHATS_DIR = get_chats_dir()
|
|
83
|
+
|
|
84
|
+
AGENT_MODE: bool = True
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def get_agent_mode() -> bool:
|
|
88
|
+
"""Returns current Agent vs Manual mode flag."""
|
|
89
|
+
return AGENT_MODE
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def set_agent_mode(mode: bool) -> None:
|
|
93
|
+
"""Sets current Agent vs Manual mode flag."""
|
|
94
|
+
global AGENT_MODE
|
|
95
|
+
AGENT_MODE = mode
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _extract_input_file_flag(args: Optional[List[str]]) -> Tuple[Optional[str], List[str]]:
|
|
99
|
+
"""Helper to detect --input-file or -f flags and extract the filepath."""
|
|
100
|
+
if not args:
|
|
101
|
+
return None, []
|
|
102
|
+
cleaned: List[str] = []
|
|
103
|
+
input_file: Optional[str] = None
|
|
104
|
+
idx = 0
|
|
105
|
+
while idx < len(args):
|
|
106
|
+
arg = args[idx]
|
|
107
|
+
if arg in ("--input-file", "-f"):
|
|
108
|
+
if idx + 1 < len(args):
|
|
109
|
+
input_file = args[idx + 1]
|
|
110
|
+
idx += 2
|
|
111
|
+
continue
|
|
112
|
+
elif arg.startswith("--input-file="):
|
|
113
|
+
input_file = arg.split("=", 1)[1]
|
|
114
|
+
idx += 1
|
|
115
|
+
continue
|
|
116
|
+
elif arg.endswith(".txt") or arg.endswith(".csv"):
|
|
117
|
+
if Path(arg).exists():
|
|
118
|
+
input_file = arg
|
|
119
|
+
idx += 1
|
|
120
|
+
continue
|
|
121
|
+
cleaned.append(arg)
|
|
122
|
+
idx += 1
|
|
123
|
+
return input_file, cleaned
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ==============================================================================
|
|
127
|
+
# 1. SCRAPER PLUGIN HANDLERS (SUBPROCESS & BATCH ROUTING)
|
|
128
|
+
# ==============================================================================
|
|
129
|
+
|
|
130
|
+
def resolve_plugin_folder(target: str) -> Optional[str]:
|
|
131
|
+
"""Dynamically resolves a command, alias, or folder name to its plugin folder name."""
|
|
132
|
+
clean = target.strip().lower().lstrip("/")
|
|
133
|
+
for p in get_active_plugins():
|
|
134
|
+
p_name = p.get("name", "").lower()
|
|
135
|
+
if clean == p_name:
|
|
136
|
+
return p["name"]
|
|
137
|
+
|
|
138
|
+
# Check CLI aliases (e.g. ['reddit', 'r'])
|
|
139
|
+
cli_aliases = [str(a).lower() for a in p.get("cli_aliases", [])]
|
|
140
|
+
if clean in cli_aliases:
|
|
141
|
+
return p["name"]
|
|
142
|
+
|
|
143
|
+
# Check slash command aliases (e.g. ['/reddit', '/r'])
|
|
144
|
+
aliases = [str(a).lower().lstrip("/") for a in p.get("aliases", [])]
|
|
145
|
+
if clean in aliases:
|
|
146
|
+
return p["name"]
|
|
147
|
+
|
|
148
|
+
# Check prefix match (e.g. 'youtube' matching 'youtube-scrape')
|
|
149
|
+
if p_name.startswith(f"{clean}-") or p_name.startswith(clean):
|
|
150
|
+
return p["name"]
|
|
151
|
+
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def handle_plugin_command(platform_or_name: str, args: Optional[List[str]] = None) -> None:
|
|
156
|
+
"""
|
|
157
|
+
Dynamically launches any scraper plugin CLI via subprocess or routes bulk targets
|
|
158
|
+
to the centralized batch extraction engine.
|
|
159
|
+
"""
|
|
160
|
+
input_file, remaining_args = _extract_input_file_flag(args)
|
|
161
|
+
if input_file:
|
|
162
|
+
run_batch_extraction(platform_or_name, input_file, remaining_args)
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
folder_name = resolve_plugin_folder(platform_or_name)
|
|
166
|
+
if not folder_name:
|
|
167
|
+
console.print(f"[bold red][!] Error: Plugin '{platform_or_name}' not found.[/bold red]")
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
cli_path = PLUGINS_DIR / folder_name / "cli.py"
|
|
171
|
+
if not cli_path.exists():
|
|
172
|
+
console.print(f"[bold red][!] Error: {folder_name}/cli.py not found.[/bold red]")
|
|
173
|
+
return
|
|
174
|
+
|
|
175
|
+
display_name = folder_name.replace("-", " ").title()
|
|
176
|
+
for p in get_active_plugins():
|
|
177
|
+
if p.get("name") == folder_name:
|
|
178
|
+
display_name = p.get("display_name", display_name)
|
|
179
|
+
break
|
|
180
|
+
|
|
181
|
+
console.print(f"[dim]Launching {display_name}...[/dim]")
|
|
182
|
+
cmd = [sys.executable, str(cli_path)]
|
|
183
|
+
if args:
|
|
184
|
+
cmd.extend(args)
|
|
185
|
+
else:
|
|
186
|
+
cmd.append("-i")
|
|
187
|
+
|
|
188
|
+
out_dir = get_outputs_dir(folder_name)
|
|
189
|
+
state_dir = get_state_dir()
|
|
190
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
state_dir.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
|
|
193
|
+
child_env = os.environ.copy()
|
|
194
|
+
child_env["SOCIALSCRAPE_OUTPUT_DIR"] = str(out_dir)
|
|
195
|
+
child_env["SOCIALSCRAPE_STATE_DIR"] = str(state_dir)
|
|
196
|
+
|
|
197
|
+
run_plugin_subprocess(cmd, cwd=get_data_dir(), env=child_env)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# Clean unified alias
|
|
201
|
+
handle_scraper_command = handle_plugin_command
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def handle_batch_command(args: Optional[List[str]] = None) -> None:
|
|
205
|
+
"""Interactive batch queue runner or direct CLI dispatcher."""
|
|
206
|
+
if args and len(args) >= 2:
|
|
207
|
+
platform = args[0]
|
|
208
|
+
input_file = args[1]
|
|
209
|
+
extra_args = args[2:]
|
|
210
|
+
run_batch_extraction(platform, input_file, extra_args)
|
|
211
|
+
return
|
|
212
|
+
|
|
213
|
+
console.print()
|
|
214
|
+
console.print(f"[{COLOR_BORDER}] ╭─ Batch Scraper Engine ──────────────────────────── esc ─╮[/{COLOR_BORDER}]")
|
|
215
|
+
console.print(f"[{COLOR_BORDER}] │[/{COLOR_BORDER}] [bold {COLOR_PRIMARY}]Run bulk extractions from .txt or .csv files with rate-limiting[/{COLOR_PRIMARY}][{COLOR_BORDER}]│[/{COLOR_BORDER}]")
|
|
216
|
+
console.print(f"[{COLOR_BORDER}] ╰───────────────────────────────────────────────────────╯[/{COLOR_BORDER}]")
|
|
217
|
+
console.print()
|
|
218
|
+
|
|
219
|
+
active = get_active_plugins()
|
|
220
|
+
for idx, p in enumerate(active, 1):
|
|
221
|
+
p_title = p.get("display_name", p["name"].replace("-", " ").title())
|
|
222
|
+
p_cmd = p.get("command", f"/{p['name']}")
|
|
223
|
+
console.print(f" [{idx}] [bold cyan]{p_title:<26}[/bold cyan] [dim]({p_cmd})[/dim]")
|
|
224
|
+
|
|
225
|
+
console.print()
|
|
226
|
+
try:
|
|
227
|
+
p_choice = pt_prompt(f"Select platform [1-{len(active)} or name] (or Enter to cancel): ").strip().lower()
|
|
228
|
+
if not p_choice:
|
|
229
|
+
return
|
|
230
|
+
|
|
231
|
+
chosen_platform = "youtube"
|
|
232
|
+
if p_choice.isdigit() and 1 <= int(p_choice) <= len(active):
|
|
233
|
+
chosen_platform = active[int(p_choice) - 1]["name"]
|
|
234
|
+
else:
|
|
235
|
+
resolved = resolve_plugin_folder(p_choice)
|
|
236
|
+
if resolved:
|
|
237
|
+
chosen_platform = resolved
|
|
238
|
+
else:
|
|
239
|
+
chosen_platform = p_choice
|
|
240
|
+
|
|
241
|
+
file_path = pt_prompt("Enter path to targets file (.txt / .csv): ").strip()
|
|
242
|
+
if not file_path:
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
flags_input = pt_prompt("Enter optional CLI flags (e.g. --download-video -q 1080p, or Enter for defaults): ").strip()
|
|
246
|
+
extra_args = flags_input.split() if flags_input else []
|
|
247
|
+
|
|
248
|
+
run_batch_extraction(chosen_platform, file_path, extra_args)
|
|
249
|
+
except (KeyboardInterrupt, EOFError):
|
|
250
|
+
pass
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def handle_resume_batch_command(args: Optional[List[str]] = None) -> None:
|
|
254
|
+
"""Resumes an incomplete or interrupted batch from its saved checkpoint."""
|
|
255
|
+
batch_id = args[0] if args else None
|
|
256
|
+
resume_batch(batch_id)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# ==============================================================================
|
|
260
|
+
# 2. HUB UTILITY & VIEW HANDLERS
|
|
261
|
+
# ==============================================================================
|
|
262
|
+
|
|
263
|
+
def handle_plugins_command(args: Optional[List[str]] = None) -> None:
|
|
264
|
+
"""Lists all active plugins in a styled table with interactive feature drilldown."""
|
|
265
|
+
plugins = get_active_plugins()
|
|
266
|
+
table = Table(title="📦 Active SocialScrape Plugins", border_style=COLOR_BORDER)
|
|
267
|
+
table.add_column("#", style=f"bold {COLOR_PRIMARY}", width=4)
|
|
268
|
+
table.add_column("Plugin Name", style=f"bold {COLOR_TEXT}")
|
|
269
|
+
table.add_column("Type", style="cyan")
|
|
270
|
+
table.add_column("Status", style="green")
|
|
271
|
+
table.add_column("Location", style=f"{COLOR_MUTED}")
|
|
272
|
+
|
|
273
|
+
for idx, p in enumerate(plugins, 1):
|
|
274
|
+
table.add_row(
|
|
275
|
+
str(idx),
|
|
276
|
+
p["name"],
|
|
277
|
+
"Python Plugin SDK",
|
|
278
|
+
"✅ Ready",
|
|
279
|
+
f"plugins/{p['name']}"
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
console.print()
|
|
283
|
+
console.print(table)
|
|
284
|
+
console.print()
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
choice = pt_prompt(f"Type plugin number [1-{len(plugins)}] or name to view full feature details (or Enter to return): ").strip()
|
|
288
|
+
if not choice:
|
|
289
|
+
return
|
|
290
|
+
|
|
291
|
+
if choice.isdigit():
|
|
292
|
+
idx = int(choice)
|
|
293
|
+
if 1 <= idx <= len(plugins):
|
|
294
|
+
chosen_plugin = plugins[idx - 1]["name"]
|
|
295
|
+
render_plugin_features(chosen_plugin)
|
|
296
|
+
return
|
|
297
|
+
else:
|
|
298
|
+
console.print(f"[bold yellow][!] Invalid plugin number {idx}. Please choose between 1 and {len(plugins)}.[/bold yellow]\n")
|
|
299
|
+
return
|
|
300
|
+
|
|
301
|
+
for p in plugins:
|
|
302
|
+
if choice.lower() in p["name"].lower():
|
|
303
|
+
render_plugin_features(p["name"])
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
render_plugin_features(choice)
|
|
307
|
+
except (KeyboardInterrupt, EOFError):
|
|
308
|
+
pass
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def handle_outputs_command() -> None:
|
|
312
|
+
"""Displays a tree of scraped outputs across all plugins."""
|
|
313
|
+
tree = Tree(f"📁 [bold {COLOR_TEXT}]SocialScrape Outputs[/bold {COLOR_TEXT}]")
|
|
314
|
+
found_any = False
|
|
315
|
+
|
|
316
|
+
for p in get_active_plugins():
|
|
317
|
+
out_dir = get_outputs_dir(p["name"])
|
|
318
|
+
if out_dir.exists():
|
|
319
|
+
p_node = tree.add(f"📦 [bold white]{p['name']}[/bold white]")
|
|
320
|
+
for sub in sorted(out_dir.iterdir()):
|
|
321
|
+
if sub.is_dir():
|
|
322
|
+
sub_node = p_node.add(f"📂 [cyan]{sub.name}/[/cyan]")
|
|
323
|
+
found_any = True
|
|
324
|
+
for item in sorted(sub.iterdir())[:10]:
|
|
325
|
+
if item.is_dir():
|
|
326
|
+
files_count = len(list(item.iterdir()))
|
|
327
|
+
sub_node.add(f"📄 [yellow]{item.name}[/yellow] ({files_count} files)")
|
|
328
|
+
else:
|
|
329
|
+
sub_node.add(f"📄 {item.name}")
|
|
330
|
+
|
|
331
|
+
console.print()
|
|
332
|
+
if found_any:
|
|
333
|
+
console.print(tree)
|
|
334
|
+
else:
|
|
335
|
+
console.print(f"[{COLOR_MUTED}]No scraped outputs found yet. Run [bold cyan]/youtube[/bold cyan] to scrape videos.[/{COLOR_MUTED}]")
|
|
336
|
+
console.print()
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def handle_readme_command() -> None:
|
|
340
|
+
"""Renders the project README in the terminal."""
|
|
341
|
+
readme_path = get_bundled_doc_path("README.md")
|
|
342
|
+
if not readme_path:
|
|
343
|
+
console.print("[bold red][!] README.md not found.[/bold red]")
|
|
344
|
+
return
|
|
345
|
+
|
|
346
|
+
with open(readme_path, "r", encoding="utf-8") as f:
|
|
347
|
+
md = Markdown(f.read())
|
|
348
|
+
console.print()
|
|
349
|
+
console.print(Panel(md, title="📖 SocialScrape README", border_style=COLOR_BORDER, padding=(1, 2)))
|
|
350
|
+
console.print()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def handle_skill_command(args: Optional[List[str]] = None, to_stdout: bool = False) -> None:
|
|
354
|
+
"""
|
|
355
|
+
Renders or dumps the Master Root SKILL.md or a specific Spoke Plugin's SKILL.md.
|
|
356
|
+
If to_stdout is True, writes clean raw Markdown directly to stdout for external AI agent consumption.
|
|
357
|
+
"""
|
|
358
|
+
target_spoke = args[0].strip().lower() if args else None
|
|
359
|
+
|
|
360
|
+
skill_file: Optional[Path] = None
|
|
361
|
+
title: str = "🤖 SocialScrape Master Agent Skill"
|
|
362
|
+
|
|
363
|
+
if target_spoke:
|
|
364
|
+
resolved_folder = resolve_plugin_folder(target_spoke)
|
|
365
|
+
if resolved_folder:
|
|
366
|
+
spoke_skill = get_plugins_dir() / resolved_folder / "SKILL.md"
|
|
367
|
+
if spoke_skill.exists():
|
|
368
|
+
skill_file = spoke_skill
|
|
369
|
+
title = f"🤖 {resolved_folder} Spoke Skill"
|
|
370
|
+
if not skill_file:
|
|
371
|
+
# Fallback check in global skills directory
|
|
372
|
+
global_skill = get_skills_dir() / target_spoke / "SKILL.md"
|
|
373
|
+
if global_skill.exists():
|
|
374
|
+
skill_file = global_skill
|
|
375
|
+
title = f"🤖 {target_spoke} Spoke Skill"
|
|
376
|
+
|
|
377
|
+
if not skill_file:
|
|
378
|
+
msg = f"[bold red][!] No SKILL.md found for plugin '{target_spoke}'. Use /skills or --skills to list available skills.[/bold red]"
|
|
379
|
+
if to_stdout:
|
|
380
|
+
sys.stdout.write(f"Error: No SKILL.md found for plugin '{target_spoke}'.\n")
|
|
381
|
+
sys.stdout.flush()
|
|
382
|
+
else:
|
|
383
|
+
console.print(msg)
|
|
384
|
+
return
|
|
385
|
+
else:
|
|
386
|
+
# Master Root SKILL.md resolution
|
|
387
|
+
skill_file = get_bundled_doc_path("SKILL.md")
|
|
388
|
+
|
|
389
|
+
if not skill_file or not skill_file.exists():
|
|
390
|
+
msg = "[bold red][!] Master SKILL.md not found.[/bold red]"
|
|
391
|
+
if to_stdout:
|
|
392
|
+
sys.stdout.write("Error: Master SKILL.md not found.\n")
|
|
393
|
+
sys.stdout.flush()
|
|
394
|
+
else:
|
|
395
|
+
console.print(msg)
|
|
396
|
+
return
|
|
397
|
+
|
|
398
|
+
try:
|
|
399
|
+
content = skill_file.read_text(encoding="utf-8")
|
|
400
|
+
except Exception as e:
|
|
401
|
+
if to_stdout:
|
|
402
|
+
sys.stdout.write(f"Error reading {skill_file}: {e}\n")
|
|
403
|
+
sys.stdout.flush()
|
|
404
|
+
else:
|
|
405
|
+
console.print(f"[bold red][!] Error reading skill file: {e}[/bold red]")
|
|
406
|
+
return
|
|
407
|
+
|
|
408
|
+
if to_stdout:
|
|
409
|
+
sys.stdout.write(content)
|
|
410
|
+
if not content.endswith("\n"):
|
|
411
|
+
sys.stdout.write("\n")
|
|
412
|
+
sys.stdout.flush()
|
|
413
|
+
else:
|
|
414
|
+
md = Markdown(content)
|
|
415
|
+
console.print()
|
|
416
|
+
console.print(Panel(md, title=title, border_style=COLOR_BORDER, padding=(1, 2)))
|
|
417
|
+
console.print()
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def handle_skills_list_command(to_stdout: bool = False) -> None:
|
|
421
|
+
"""Lists all active spoke plugins, their trigger patterns, and skill documentation."""
|
|
422
|
+
plugins = get_active_plugins()
|
|
423
|
+
if to_stdout:
|
|
424
|
+
sys.stdout.write("SocialScrape Active Agent Skills:\n")
|
|
425
|
+
sys.stdout.write(f"{'Plugin Name':<28} {'Command':<16} {'Trigger Patterns'}\n")
|
|
426
|
+
sys.stdout.write("-" * 80 + "\n")
|
|
427
|
+
for p in plugins:
|
|
428
|
+
name = p.get("name", "")
|
|
429
|
+
cmd = p.get("command", "")
|
|
430
|
+
patterns = ", ".join(p.get("url_patterns", []))
|
|
431
|
+
sys.stdout.write(f"{name:<28} {cmd:<16} {patterns}\n")
|
|
432
|
+
sys.stdout.write("\nTo view full skill specification: socialscrape --skill <plugin-name>\n")
|
|
433
|
+
sys.stdout.flush()
|
|
434
|
+
return
|
|
435
|
+
|
|
436
|
+
table = Table(title="🤖 SocialScrape Active Agent Skills & Plugins", border_style=COLOR_BORDER)
|
|
437
|
+
table.add_column("#", style="bold cyan", width=4)
|
|
438
|
+
table.add_column("Plugin Name", style="bold white", width=26)
|
|
439
|
+
table.add_column("Command", style="cyan", width=14)
|
|
440
|
+
table.add_column("Skill File", style="green", width=12)
|
|
441
|
+
table.add_column("Primary Triggers / Domains", style="dim", width=35)
|
|
442
|
+
|
|
443
|
+
for idx, p in enumerate(plugins, 1):
|
|
444
|
+
name = p.get("name", "")
|
|
445
|
+
cmd = p.get("command", f"/{name}")
|
|
446
|
+
has_skill = "✅ Ready" if p.get("skill") else "❌ Missing"
|
|
447
|
+
patterns = ", ".join(p.get("url_patterns", []))
|
|
448
|
+
table.add_row(str(idx), name, cmd, has_skill, patterns[:35])
|
|
449
|
+
|
|
450
|
+
console.print()
|
|
451
|
+
console.print(table)
|
|
452
|
+
console.print("\n[dim]Tip: Type [bold cyan]/skill <name>[/bold cyan] or run [bold cyan]socialscrape --skill <name>[/bold cyan] to inspect full parameter schemas.[/dim]\n")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def handle_fix_command() -> None:
|
|
456
|
+
"""Repairs dependencies by running pip install."""
|
|
457
|
+
pkg_dir = get_package_dir()
|
|
458
|
+
req_path = pkg_dir / "requirements.txt"
|
|
459
|
+
if not req_path.exists():
|
|
460
|
+
req_path = ROOT_DIR / "requirements.txt"
|
|
461
|
+
console.print("[bold yellow]🔧 Repairing SocialScrape dependencies...[/bold yellow]")
|
|
462
|
+
try:
|
|
463
|
+
if req_path.exists():
|
|
464
|
+
cmd = [sys.executable, "-m", "pip", "install", "-r", str(req_path)]
|
|
465
|
+
res = subprocess.run(cmd, cwd=pkg_dir)
|
|
466
|
+
else:
|
|
467
|
+
core_deps = [
|
|
468
|
+
"rich>=13.0.0",
|
|
469
|
+
"prompt-toolkit>=3.0.0",
|
|
470
|
+
"art>=6.0",
|
|
471
|
+
"requests>=2.28.0",
|
|
472
|
+
"yt-dlp>=2024.0.0",
|
|
473
|
+
"youtube-transcript-api>=1.0.0",
|
|
474
|
+
"python-dotenv>=1.0.0",
|
|
475
|
+
"platformdirs>=3.0.0",
|
|
476
|
+
]
|
|
477
|
+
cmd = [sys.executable, "-m", "pip", "install", "--upgrade", *core_deps]
|
|
478
|
+
res = subprocess.run(cmd)
|
|
479
|
+
if res.returncode == 0:
|
|
480
|
+
console.print("[bold green]✅ Dependencies successfully verified and repaired![/bold green]")
|
|
481
|
+
if os.environ.get("SOCIALSCRAPE_NPM_LAUNCHER") == "1":
|
|
482
|
+
console.print("[dim]Tip: To rebuild the isolated runtime environment cleanly, run: socialscrape --setup[/dim]")
|
|
483
|
+
else:
|
|
484
|
+
console.print(f"[bold red][!] Pip repair exited with code {res.returncode}.[/bold red]")
|
|
485
|
+
if os.environ.get("SOCIALSCRAPE_NPM_LAUNCHER") == "1":
|
|
486
|
+
console.print("[dim]Tip: Run 'socialscrape --setup' outside the TUI to recreate the isolated Python runtime.[/dim]")
|
|
487
|
+
except Exception as e:
|
|
488
|
+
console.print(f"[bold red][!] Fix failed: {e}[/bold red]")
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
# ==============================================================================
|
|
492
|
+
# 3. SESSION MANAGEMENT HANDLERS
|
|
493
|
+
# ==============================================================================
|
|
494
|
+
|
|
495
|
+
def handle_new_command(version: str = "2.0.2") -> None:
|
|
496
|
+
"""Starts a fresh new chat session without needing to restart the terminal."""
|
|
497
|
+
session_id = init_new_chat_session()
|
|
498
|
+
display_home_screen(version=version)
|
|
499
|
+
render_action_card(f"[bold green]✨ Started fresh chat session: {session_id}[/bold green]")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def handle_history_command() -> None:
|
|
503
|
+
"""Opens the interactive scrollable chat history & scrollback viewer."""
|
|
504
|
+
open_chat_history_viewer(get_conversation_history(), get_openrouter_model())
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def handle_clear_command(version: str = "2.0.2") -> None:
|
|
508
|
+
"""Clears all conversation messages for the current session and purges mouse modes."""
|
|
509
|
+
set_conversation_history([])
|
|
510
|
+
save_chat_session()
|
|
511
|
+
reset_terminal_mouse_mode()
|
|
512
|
+
display_home_screen(version=version)
|
|
513
|
+
render_action_card("[dim]🧹 Cleared chat history for active session.[/dim]")
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def handle_resume_command(version: str = "2.0.2") -> None:
|
|
517
|
+
"""
|
|
518
|
+
Renders an interactive session picker modal allowing the user to select
|
|
519
|
+
and resume a previously saved chat session from chats/.
|
|
520
|
+
"""
|
|
521
|
+
CHATS_DIR.mkdir(parents=True, exist_ok=True)
|
|
522
|
+
session_files = sorted(CHATS_DIR.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
523
|
+
|
|
524
|
+
if not session_files:
|
|
525
|
+
render_action_card("[bold yellow]⚠️ No saved chat sessions found in chats/.[/bold yellow]")
|
|
526
|
+
return
|
|
527
|
+
|
|
528
|
+
sessions_data = []
|
|
529
|
+
for f in session_files:
|
|
530
|
+
try:
|
|
531
|
+
with open(f, "r", encoding="utf-8") as fp:
|
|
532
|
+
data = json.load(fp)
|
|
533
|
+
sessions_data.append((f, data))
|
|
534
|
+
except (json.JSONDecodeError, IOError, OSError, PermissionError) as e:
|
|
535
|
+
console.print(f"[dim yellow]⚠️ Notice: Skipped unreadable session file '{f.name}': {e}[/dim yellow]")
|
|
536
|
+
continue
|
|
537
|
+
|
|
538
|
+
if not sessions_data:
|
|
539
|
+
render_action_card("[bold yellow]⚠️ No valid chat sessions found to resume.[/bold yellow]")
|
|
540
|
+
return
|
|
541
|
+
|
|
542
|
+
table = Table(
|
|
543
|
+
title="📂 Saved Chat Sessions (Select to Resume)",
|
|
544
|
+
border_style=COLOR_BORDER,
|
|
545
|
+
show_header=True
|
|
546
|
+
)
|
|
547
|
+
table.add_column("#", style=f"bold {COLOR_PRIMARY}", width=4)
|
|
548
|
+
table.add_column("Session Title / First Query", style=f"bold {COLOR_TEXT}", width=38)
|
|
549
|
+
table.add_column("Last Active", style=f"{COLOR_MUTED}", width=19)
|
|
550
|
+
table.add_column("Model", style="cyan", width=22)
|
|
551
|
+
table.add_column("Turns", style="green", width=6)
|
|
552
|
+
|
|
553
|
+
curr_session_id = get_current_session_id()
|
|
554
|
+
for idx, (f, data) in enumerate(sessions_data, 1):
|
|
555
|
+
s_id = data.get("session_id", f.stem)
|
|
556
|
+
title = data.get("title", "Empty Session")
|
|
557
|
+
created = data.get("created_at", "")
|
|
558
|
+
model_name = data.get("active_model", "").split("/")[-1]
|
|
559
|
+
msg_count = len(data.get("messages", []))
|
|
560
|
+
is_active = (s_id == curr_session_id)
|
|
561
|
+
active_mark = " [bold green]● ACTIVE[/bold green]" if is_active else ""
|
|
562
|
+
|
|
563
|
+
table.add_row(
|
|
564
|
+
str(idx),
|
|
565
|
+
f"{title[:35]}{active_mark}",
|
|
566
|
+
created,
|
|
567
|
+
model_name,
|
|
568
|
+
str(msg_count)
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
console.print()
|
|
572
|
+
console.print(table)
|
|
573
|
+
console.print()
|
|
574
|
+
|
|
575
|
+
try:
|
|
576
|
+
choice = pt_prompt(f"Select session number [1-{len(sessions_data)}] to resume (or Enter to cancel): ").strip()
|
|
577
|
+
if not choice:
|
|
578
|
+
return
|
|
579
|
+
|
|
580
|
+
idx = int(choice) - 1
|
|
581
|
+
if 0 <= idx < len(sessions_data):
|
|
582
|
+
f, selected_data = sessions_data[idx]
|
|
583
|
+
new_id = selected_data.get("session_id", f.stem)
|
|
584
|
+
new_history = selected_data.get("messages", [])
|
|
585
|
+
set_current_session_id(new_id)
|
|
586
|
+
set_conversation_history(new_history)
|
|
587
|
+
|
|
588
|
+
# Redraw home screen and replay messages into the console buffer
|
|
589
|
+
display_home_screen(version=version)
|
|
590
|
+
for msg in new_history:
|
|
591
|
+
role = msg.get("role")
|
|
592
|
+
content = msg.get("content", "")
|
|
593
|
+
if role == "user" and not content.startswith("[System Observation"):
|
|
594
|
+
render_user_message(content)
|
|
595
|
+
elif role == "assistant" and content:
|
|
596
|
+
render_ai_response(content, selected_data.get("active_model", "SocialScrape AI"))
|
|
597
|
+
|
|
598
|
+
render_action_card(f"[bold green]🔄 Resumed session: {new_id} ({len(new_history)} turns loaded)[/bold green]")
|
|
599
|
+
else:
|
|
600
|
+
render_action_card("[bold yellow]Invalid session selection.[/bold yellow]")
|
|
601
|
+
except ValueError:
|
|
602
|
+
render_action_card("[bold yellow]Invalid number entered.[/bold yellow]")
|
|
603
|
+
except (KeyboardInterrupt, EOFError):
|
|
604
|
+
pass
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def handle_delete_command(args: Optional[List[str]] = None) -> None:
|
|
608
|
+
"""
|
|
609
|
+
Renders an interactive session deletion modal or deletes a specific session.
|
|
610
|
+
"""
|
|
611
|
+
CHATS_DIR.mkdir(parents=True, exist_ok=True)
|
|
612
|
+
session_files = sorted(CHATS_DIR.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
613
|
+
|
|
614
|
+
if not session_files:
|
|
615
|
+
render_action_card("[bold yellow]⚠️ No saved chat sessions found in chats/ to delete.[/bold yellow]")
|
|
616
|
+
return
|
|
617
|
+
|
|
618
|
+
curr_session_id = get_current_session_id()
|
|
619
|
+
|
|
620
|
+
# Check if user typed "/delete all"
|
|
621
|
+
if args and args[0].lower() in ("all", "--all", "-a"):
|
|
622
|
+
for f in session_files:
|
|
623
|
+
try:
|
|
624
|
+
f.unlink()
|
|
625
|
+
except (OSError, IOError, PermissionError) as e:
|
|
626
|
+
console.print(f"[dim red]Warning: Could not delete '{f.name}': {e}[/dim red]")
|
|
627
|
+
init_new_chat_session()
|
|
628
|
+
render_action_card("[bold red]🗑️ All chat sessions deleted. Started fresh new session.[/bold red]")
|
|
629
|
+
return
|
|
630
|
+
|
|
631
|
+
sessions_data = []
|
|
632
|
+
for f in session_files:
|
|
633
|
+
try:
|
|
634
|
+
with open(f, "r", encoding="utf-8") as fp:
|
|
635
|
+
data = json.load(fp)
|
|
636
|
+
sessions_data.append((f, data))
|
|
637
|
+
except (json.JSONDecodeError, IOError, OSError, PermissionError):
|
|
638
|
+
continue
|
|
639
|
+
|
|
640
|
+
table = Table(
|
|
641
|
+
title="🗑️ Delete Chat Session",
|
|
642
|
+
border_style="red",
|
|
643
|
+
show_header=True
|
|
644
|
+
)
|
|
645
|
+
table.add_column("#", style="bold red", width=4)
|
|
646
|
+
table.add_column("Session Title / First Query", style=f"bold {COLOR_TEXT}", width=38)
|
|
647
|
+
table.add_column("Last Active", style=f"{COLOR_MUTED}", width=19)
|
|
648
|
+
table.add_column("Turns", style="cyan", width=6)
|
|
649
|
+
|
|
650
|
+
for idx, (f, data) in enumerate(sessions_data, 1):
|
|
651
|
+
s_id = data.get("session_id", f.stem)
|
|
652
|
+
title = data.get("title", "Empty Session")
|
|
653
|
+
created = data.get("created_at", "")
|
|
654
|
+
msg_count = len(data.get("messages", []))
|
|
655
|
+
is_active = (s_id == curr_session_id)
|
|
656
|
+
active_mark = " [bold yellow](Current Active)[/bold yellow]" if is_active else ""
|
|
657
|
+
|
|
658
|
+
table.add_row(
|
|
659
|
+
str(idx),
|
|
660
|
+
f"{title[:35]}{active_mark}",
|
|
661
|
+
created,
|
|
662
|
+
str(msg_count)
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
table.add_row("A", "[bold red]Delete ALL saved sessions[/bold red]", "-", "-")
|
|
666
|
+
|
|
667
|
+
console.print()
|
|
668
|
+
console.print(table)
|
|
669
|
+
console.print()
|
|
670
|
+
|
|
671
|
+
try:
|
|
672
|
+
choice = pt_prompt(f"Select session to delete [1-{len(sessions_data)}, A] (or Enter to cancel): ").strip()
|
|
673
|
+
if not choice:
|
|
674
|
+
return
|
|
675
|
+
|
|
676
|
+
if choice.upper() == "A":
|
|
677
|
+
for f in session_files:
|
|
678
|
+
try:
|
|
679
|
+
f.unlink()
|
|
680
|
+
except (OSError, IOError, PermissionError) as e:
|
|
681
|
+
console.print(f"[dim red]Warning: Could not delete '{f.name}': {e}[/dim red]")
|
|
682
|
+
init_new_chat_session()
|
|
683
|
+
render_action_card("[bold red]🗑️ All chat sessions deleted. Started fresh new session.[/bold red]")
|
|
684
|
+
return
|
|
685
|
+
|
|
686
|
+
idx = int(choice) - 1
|
|
687
|
+
if 0 <= idx < len(sessions_data):
|
|
688
|
+
f, selected_data = sessions_data[idx]
|
|
689
|
+
deleted_id = selected_data.get("session_id", f.stem)
|
|
690
|
+
try:
|
|
691
|
+
f.unlink()
|
|
692
|
+
except (OSError, IOError, PermissionError) as e:
|
|
693
|
+
render_action_card(f"[bold red][!] Error deleting session '{deleted_id}': {e}[/bold red]")
|
|
694
|
+
return
|
|
695
|
+
|
|
696
|
+
if deleted_id == curr_session_id:
|
|
697
|
+
init_new_chat_session()
|
|
698
|
+
render_action_card(f"[bold red]🗑️ Deleted active session ({deleted_id}). Started fresh new session.[/bold red]")
|
|
699
|
+
else:
|
|
700
|
+
render_action_card(f"[bold red]🗑️ Deleted session: {deleted_id}[/bold red]")
|
|
701
|
+
else:
|
|
702
|
+
render_action_card("[bold yellow]Invalid selection.[/bold yellow]")
|
|
703
|
+
except ValueError:
|
|
704
|
+
render_action_card("[bold yellow]Invalid option entered.[/bold yellow]")
|
|
705
|
+
except (KeyboardInterrupt, EOFError):
|
|
706
|
+
pass
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
# ==============================================================================
|
|
710
|
+
# 4. CONFIGURATION & MAINTENANCE HANDLERS
|
|
711
|
+
# ==============================================================================
|
|
712
|
+
|
|
713
|
+
def handle_update_command() -> None:
|
|
714
|
+
"""Safely pulls latest commits from GitHub or guides npm/pip upgrades."""
|
|
715
|
+
pkg_dir = get_package_dir()
|
|
716
|
+
console.print("[bold yellow]⚡ Checking for updates...[/bold yellow]")
|
|
717
|
+
try:
|
|
718
|
+
git_root = pkg_dir if (pkg_dir / ".git").exists() else (
|
|
719
|
+
pkg_dir.parent.parent if pkg_dir.name == "PPA" and (pkg_dir.parent.parent / ".git").exists() else None
|
|
720
|
+
)
|
|
721
|
+
custom_update_url = os.environ.get("SOCIALSCRAPE_UPDATE_URL", "").strip()
|
|
722
|
+
|
|
723
|
+
if git_root:
|
|
724
|
+
res = subprocess.run(["git", "pull", "origin", "main"], cwd=git_root, capture_output=True, text=True)
|
|
725
|
+
if res.returncode == 0:
|
|
726
|
+
if "Already up to date" in res.stdout:
|
|
727
|
+
console.print("[bold green]✨ You are on the latest version of SocialScrape![/bold green]")
|
|
728
|
+
else:
|
|
729
|
+
console.print(f"[bold green]✅ Git pull successful:\n{res.stdout}[/bold green]")
|
|
730
|
+
console.print("[cyan]Re-installing package to apply updates...[/cyan]")
|
|
731
|
+
subprocess.run([sys.executable, "-m", "pip", "install", "-e", "."], cwd=pkg_dir)
|
|
732
|
+
console.print("[bold green]Update successful! Please restart SocialScrape.[/bold green]")
|
|
733
|
+
else:
|
|
734
|
+
console.print(f"[bold red][!] Git pull error: {res.stderr}[/bold red]")
|
|
735
|
+
elif os.environ.get("SOCIALSCRAPE_NPM_LAUNCHER") == "1" and not custom_update_url:
|
|
736
|
+
console.print("[cyan]SocialScrape is managed via the @auscera/socialscrape CLI runtime.[/cyan]")
|
|
737
|
+
console.print(" Update globally with: [bold white]pnpm add -g @auscera/socialscrape@latest[/bold white]")
|
|
738
|
+
console.print(" Or with npm: [bold white]npm install -g @auscera/socialscrape@latest[/bold white]")
|
|
739
|
+
console.print(" Or run ephemeral: [bold white]pnpm dlx @auscera/socialscrape@latest[/bold white]")
|
|
740
|
+
else:
|
|
741
|
+
update_target = (
|
|
742
|
+
custom_update_url
|
|
743
|
+
or str(load_config().get("update_url", "")).strip()
|
|
744
|
+
or "git+https://github.com/delightc123/social-scrape.git#subdirectory=apps/PPA"
|
|
745
|
+
)
|
|
746
|
+
console.print("[cyan]Upgrading SocialScrape via pip...[/cyan]")
|
|
747
|
+
res = subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", update_target], capture_output=True, text=True)
|
|
748
|
+
if res.returncode == 0:
|
|
749
|
+
console.print("[bold green]✨ SocialScrape upgraded successfully! Please restart SocialScrape.[/bold green]")
|
|
750
|
+
else:
|
|
751
|
+
console.print(f"[bold red][!] Pip upgrade error: {res.stderr}[/bold red]")
|
|
752
|
+
except Exception as e:
|
|
753
|
+
console.print(f"[bold red][!] Update check failed: {e}[/bold red]")
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def handle_config_command() -> None:
|
|
757
|
+
"""Interactive configuration editor for global settings."""
|
|
758
|
+
cfg = load_config()
|
|
759
|
+
console.print("\n[bold cyan]⚙️ SocialScrape Configuration Settings[/bold cyan]")
|
|
760
|
+
console.print(f"[dim]Stored in: {get_config_path()}[/dim]\n")
|
|
761
|
+
|
|
762
|
+
console.print(f"1. Default Quality: [bold yellow]{cfg.get('default_quality', '1080p')}[/bold yellow]")
|
|
763
|
+
console.print(f"2. Default Output Format: [bold yellow]{cfg.get('default_output_format', 'mp4')}[/bold yellow]")
|
|
764
|
+
console.print(f"3. Active OpenRouter Model: [bold yellow]{cfg.get('openrouter_model', 'cohere/north-mini-code:free')}[/bold yellow]")
|
|
765
|
+
console.print(f"4. Default AI Agent Mode: [bold yellow]{cfg.get('agent_mode_default', True)}[/bold yellow]")
|
|
766
|
+
alt_screen_active = cfg.get('alternate_screen_buffer', False)
|
|
767
|
+
console.print(f"5. Alternate Screen Buffer: [bold yellow]{'Enabled (Full-Screen OpenCode Mode)' if alt_screen_active else 'Disabled (Native Terminal Scrollbar)'}[/bold yellow]\n")
|
|
768
|
+
|
|
769
|
+
try:
|
|
770
|
+
choice = pt_prompt("Select an option to edit (1-5, or Enter to cancel): ").strip()
|
|
771
|
+
if choice == "1":
|
|
772
|
+
q = pt_prompt("Enter default quality (1080p/720p/480p/best): ").strip()
|
|
773
|
+
if q:
|
|
774
|
+
cfg["default_quality"] = q
|
|
775
|
+
save_config(cfg)
|
|
776
|
+
render_action_card("[bold green]✅ Default quality updated![/bold green]")
|
|
777
|
+
elif choice == "2":
|
|
778
|
+
fmt = pt_prompt("Enter default format (mp4/m4a/mp3): ").strip()
|
|
779
|
+
if fmt:
|
|
780
|
+
cfg["default_output_format"] = fmt
|
|
781
|
+
save_config(cfg)
|
|
782
|
+
render_action_card("[bold green]✅ Default output format updated![/bold green]")
|
|
783
|
+
elif choice == "3":
|
|
784
|
+
handle_models_command()
|
|
785
|
+
elif choice == "4":
|
|
786
|
+
mode_input = pt_prompt("Enable Agent Mode by default? (y/n): ").strip().lower()
|
|
787
|
+
if mode_input in ("y", "yes"):
|
|
788
|
+
cfg["agent_mode_default"] = True
|
|
789
|
+
set_agent_mode(True)
|
|
790
|
+
elif mode_input in ("n", "no"):
|
|
791
|
+
cfg["agent_mode_default"] = False
|
|
792
|
+
set_agent_mode(False)
|
|
793
|
+
save_config(cfg)
|
|
794
|
+
render_action_card("[bold green]✅ Default agent mode updated![/bold green]")
|
|
795
|
+
elif choice == "5":
|
|
796
|
+
new_val = not cfg.get("alternate_screen_buffer", False)
|
|
797
|
+
cfg["alternate_screen_buffer"] = new_val
|
|
798
|
+
save_config(cfg)
|
|
799
|
+
status_str = "Enabled (Full-Screen OpenCode Mode)" if new_val else "Disabled (Native Terminal Scrollbar)"
|
|
800
|
+
render_action_card(f"[bold green]✅ Alternate Screen Buffer updated: {status_str}![/bold green]\n ┃ [dim]Takes effect on next CLI startup.[/dim]")
|
|
801
|
+
except (KeyboardInterrupt, EOFError):
|
|
802
|
+
pass
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def handle_uninstall_command() -> None:
|
|
806
|
+
"""Prints clean uninstall instructions."""
|
|
807
|
+
data_dir = get_data_dir()
|
|
808
|
+
cfg_dir = get_config_dir()
|
|
809
|
+
console.print("\n[bold yellow]🗑️ To completely uninstall SocialScrape:[/bold yellow]")
|
|
810
|
+
console.print(" 1. Run in terminal: [bold cyan]pip uninstall socialscrape[/bold cyan]")
|
|
811
|
+
console.print(f" 2. (Optional) Delete global data folder: [bold cyan]{data_dir}[/bold cyan]")
|
|
812
|
+
if cfg_dir != data_dir:
|
|
813
|
+
console.print(f" 3. (Optional) Delete global config folder: [bold cyan]{cfg_dir}[/bold cyan]")
|
|
814
|
+
console.print()
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def handle_models_command(args: Optional[List[str]] = None) -> None:
|
|
818
|
+
"""Displays the clean OpenCode model list with direct number selection [1-8]."""
|
|
819
|
+
current_model = get_openrouter_model()
|
|
820
|
+
|
|
821
|
+
console.print()
|
|
822
|
+
console.print(f"[{COLOR_BORDER}] ╭─ Select Model ────────────────────────────────── esc ─╮[/{COLOR_BORDER}]")
|
|
823
|
+
console.print(f"[{COLOR_BORDER}] │ │[/{COLOR_BORDER}]")
|
|
824
|
+
console.print(f"[{COLOR_BORDER}] │[/{COLOR_BORDER}] [bold {COLOR_ACCENT}]Recent (Free Tier)[/bold {COLOR_ACCENT}] [{COLOR_BORDER}]│[/{COLOR_BORDER}]")
|
|
825
|
+
|
|
826
|
+
for idx, m in enumerate(ALLOWED_OPENROUTER_MODELS, 1):
|
|
827
|
+
is_active = (m["id"] == current_model)
|
|
828
|
+
active_badge = "[bold green]● ACTIVE[/bold green]" if is_active else ""
|
|
829
|
+
color = COLOR_PRIMARY if is_active else COLOR_TEXT
|
|
830
|
+
|
|
831
|
+
display_line = f" [{idx}] {m['name']:<32} OpenRouter {active_badge}"
|
|
832
|
+
console.print(f"[{COLOR_BORDER}] │[/{COLOR_BORDER}] [{color}]{display_line:<49}[/{color}][{COLOR_BORDER}]│[/{COLOR_BORDER}]")
|
|
833
|
+
|
|
834
|
+
console.print(f"[{COLOR_BORDER}] │ │[/{COLOR_BORDER}]")
|
|
835
|
+
console.print(f"[{COLOR_BORDER}] ╰───────────────────────────────────────────────────────╯[/{COLOR_BORDER}]")
|
|
836
|
+
console.print()
|
|
837
|
+
|
|
838
|
+
try:
|
|
839
|
+
choice = pt_prompt("Select model [1-8] (or Enter to keep current): ").strip()
|
|
840
|
+
if not choice:
|
|
841
|
+
return
|
|
842
|
+
if choice.isdigit():
|
|
843
|
+
idx = int(choice) - 1
|
|
844
|
+
if 0 <= idx < len(ALLOWED_OPENROUTER_MODELS):
|
|
845
|
+
chosen = ALLOWED_OPENROUTER_MODELS[idx]["id"]
|
|
846
|
+
save_openrouter_model(chosen)
|
|
847
|
+
render_action_card(f"[bold green]Active AI model set to: {chosen}[/bold green]")
|
|
848
|
+
else:
|
|
849
|
+
console.print("[bold red][!] Invalid number. Choose between 1 and 8.[/bold red]")
|
|
850
|
+
else:
|
|
851
|
+
matching = [m for m in ALLOWED_OPENROUTER_MODELS if choice.lower() in m["id"].lower() or choice.lower() in m["name"].lower()]
|
|
852
|
+
if matching:
|
|
853
|
+
chosen = matching[0]["id"]
|
|
854
|
+
save_openrouter_model(chosen)
|
|
855
|
+
render_action_card(f"[bold green]Active AI model set to: {chosen}[/bold green]")
|
|
856
|
+
except (KeyboardInterrupt, EOFError):
|
|
857
|
+
pass
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def handle_agent_command() -> None:
|
|
861
|
+
"""Activates AI Agent Mode for natural language query execution."""
|
|
862
|
+
set_agent_mode(True)
|
|
863
|
+
render_action_card(
|
|
864
|
+
f"[bold #5c9cf5]🤖 Agent Mode Activated[/bold #5c9cf5]\n"
|
|
865
|
+
f" ┃ [{COLOR_MUTED}]Natural language queries are sent to OpenRouter ([bold #fab283]{get_openrouter_model()}[/bold #fab283]).[/{COLOR_MUTED}]"
|
|
866
|
+
)
|
|
867
|
+
get_openrouter_api_key(prompt_if_missing=True)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def handle_manual_command() -> None:
|
|
871
|
+
"""Activates Manual Mode, bypassing AI routing."""
|
|
872
|
+
set_agent_mode(False)
|
|
873
|
+
render_action_card(
|
|
874
|
+
f"[bold yellow]⌨️ Manual Mode Activated[/bold yellow]\n"
|
|
875
|
+
f" ┃ [{COLOR_MUTED}]AI routing disabled. Type direct slash commands (e.g., [bold cyan]/youtube[/bold cyan], [bold cyan]/models[/bold cyan]).[/{COLOR_MUTED}]"
|
|
876
|
+
)
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def handle_help_command() -> None:
|
|
880
|
+
"""Displays the full command matrix."""
|
|
881
|
+
table = Table(title="💡 SocialScrape Universal Commands", border_style=COLOR_BORDER)
|
|
882
|
+
table.add_column("Command", style=f"bold {COLOR_PRIMARY}")
|
|
883
|
+
table.add_column("Description", style=f"{COLOR_TEXT}")
|
|
884
|
+
table.add_column("Shortcut", style=f"{COLOR_MUTED}")
|
|
885
|
+
|
|
886
|
+
table.add_row("/agent", "Enable AI Agent Mode (natural language routing)", "ctrl+x a")
|
|
887
|
+
table.add_row("/manual", "Enable Manual Mode (direct slash commands)", "ctrl+x m")
|
|
888
|
+
table.add_row("/help", "Display this command matrix", "ctrl+x h")
|
|
889
|
+
table.add_row("/batch", "Run bulk batch scrape from .txt/.csv input file", "-")
|
|
890
|
+
table.add_row("/resume-batch", "Resume an interrupted/incomplete batch from checkpoint", "-")
|
|
891
|
+
table.add_row("/plugins", "List all discovered plugins with interactive drilldown", "ctrl+x p")
|
|
892
|
+
table.add_row("/models", "Browse & select active OpenRouter AI model", "ctrl+x o")
|
|
893
|
+
table.add_row("/youtube", "Download transcripts, metadata, comments & 4K video", "ctrl+x y")
|
|
894
|
+
table.add_row("/instagram", "Scrape profiles, reels, posts, comments & download MP4s", "ctrl+x i")
|
|
895
|
+
table.add_row("/tiktok", "Extract captions, feeds & watermark-free MP4s", "ctrl+x t")
|
|
896
|
+
table.add_row("/linkedin", "Scrape member profiles & company intelligence safely", "ctrl+x k")
|
|
897
|
+
table.add_row("/twitter", "Extract tweet threads, timelines & download MP4/GIFs", "ctrl+x w")
|
|
898
|
+
table.add_row("/reddit", "Extract subreddit discussions, comments & v.redd.it media", "-")
|
|
899
|
+
table.add_row("/threads", "Scrape Meta Threads user feeds & discussions", "-")
|
|
900
|
+
table.add_row("/pinterest", "Scrape pins, visual searches & download high-res media", "-")
|
|
901
|
+
table.add_row("/meta", "Search Meta Ad Library active campaigns & video ads", "-")
|
|
902
|
+
table.add_row("/outputs", "View all scraped folders and extracted media", "ctrl+x d")
|
|
903
|
+
table.add_row("/new", "Start a fresh new chat session (zero history)", "ctrl+x n")
|
|
904
|
+
table.add_row("/history", "Interactive scrollable chat history & scrollback", "pageup / ctrl+u")
|
|
905
|
+
table.add_row("/clear", "Clear message history of current session & screen", "ctrl+l")
|
|
906
|
+
table.add_row("/resume", "Interactive browser to resume a saved session", "ctrl+x r")
|
|
907
|
+
table.add_row("/delete", "Delete saved session logs from disk", "-")
|
|
908
|
+
table.add_row("/readme", "View full formatted project README documentation", "-")
|
|
909
|
+
table.add_row("/skills", "List active plugin skills & trigger patterns", "-")
|
|
910
|
+
table.add_row("/doctor", "Comprehensive environment, storage & engine diagnostics", "-")
|
|
911
|
+
table.add_row("/config", "View & edit global preferences and configuration", "-")
|
|
912
|
+
table.add_row("/fix", "Reinstall and repair all package dependencies", "-")
|
|
913
|
+
table.add_row("/update", "Safely pull latest updates from remote repository", "-")
|
|
914
|
+
table.add_row("/uninstall", "Display instructions to completely uninstall SocialScrape", "-")
|
|
915
|
+
table.add_row("/exit", "Gracefully terminate SocialScrape session", "ctrl+c / ctrl+d")
|
|
916
|
+
|
|
917
|
+
console.print()
|
|
918
|
+
console.print(table)
|
|
919
|
+
console.print()
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def handle_doctor(app: Any = None, **kwargs) -> None:
|
|
923
|
+
"""Performs comprehensive system diagnostics on runtime, storage, and scraper engines."""
|
|
924
|
+
import platform
|
|
925
|
+
from storage import (
|
|
926
|
+
is_local_mode, get_data_dir, get_config_dir,
|
|
927
|
+
get_plugins_dir, get_chats_dir,
|
|
928
|
+
plugin_registry,
|
|
929
|
+
)
|
|
930
|
+
from ui import render_doctor_report
|
|
931
|
+
|
|
932
|
+
try:
|
|
933
|
+
import yt_dlp
|
|
934
|
+
has_yt_dlp = True
|
|
935
|
+
except ImportError:
|
|
936
|
+
has_yt_dlp = False
|
|
937
|
+
|
|
938
|
+
try:
|
|
939
|
+
import youtube_transcript_api
|
|
940
|
+
has_transcript_api = True
|
|
941
|
+
except ImportError:
|
|
942
|
+
has_transcript_api = False
|
|
943
|
+
|
|
944
|
+
chats_dir = get_chats_dir()
|
|
945
|
+
chats_count = len(list(chats_dir.glob("*.json"))) if chats_dir.exists() else 0
|
|
946
|
+
plugins = plugin_registry.list_plugins()
|
|
947
|
+
|
|
948
|
+
api_key = get_openrouter_api_key(prompt_if_missing=False)
|
|
949
|
+
key_masked = f"{api_key[:8]}...{api_key[-4:]}" if len(api_key) > 12 else ("Configured" if api_key else "Missing")
|
|
950
|
+
|
|
951
|
+
from socialscrape_cli import __version__
|
|
952
|
+
|
|
953
|
+
diagnostics = {
|
|
954
|
+
"is_global": not is_local_mode(),
|
|
955
|
+
"python_version": platform.python_version(),
|
|
956
|
+
"python_path": sys.executable,
|
|
957
|
+
"package_version": __version__,
|
|
958
|
+
"data_dir": get_data_dir(),
|
|
959
|
+
"config_dir": get_config_dir(),
|
|
960
|
+
"plugins_dir": get_plugins_dir(),
|
|
961
|
+
"plugins_count": len(plugins),
|
|
962
|
+
"chats_dir": chats_dir,
|
|
963
|
+
"chats_count": chats_count,
|
|
964
|
+
"has_yt_dlp": has_yt_dlp,
|
|
965
|
+
"has_transcript_api": has_transcript_api,
|
|
966
|
+
"api_key_configured": bool(api_key),
|
|
967
|
+
"api_key_masked": key_masked,
|
|
968
|
+
"active_model": get_openrouter_model(),
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
render_doctor_report(diagnostics)
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
class CommandRouter:
|
|
975
|
+
"""Routes CLI inputs and slash commands to appropriate handlers."""
|
|
976
|
+
|
|
977
|
+
def __init__(self):
|
|
978
|
+
self._handlers: Dict[str, Callable[..., Any]] = {}
|
|
979
|
+
self._metadata: Dict[str, str] = {}
|
|
980
|
+
self._register_default_commands()
|
|
981
|
+
|
|
982
|
+
def register(self, command: str, handler: Callable[..., Any], description: Optional[str] = None, is_alias: bool = False) -> None:
|
|
983
|
+
cmd = command.lower().strip()
|
|
984
|
+
if not cmd.startswith("/"):
|
|
985
|
+
cmd = f"/{cmd}"
|
|
986
|
+
self._handlers[cmd] = handler
|
|
987
|
+
# Only add to metadata if it is a canonical command with description and not an alias
|
|
988
|
+
if not is_alias and description:
|
|
989
|
+
self._metadata[cmd] = description
|
|
990
|
+
|
|
991
|
+
def _register_default_commands(self) -> None:
|
|
992
|
+
# Canonical PPA Slash Commands (Strictly One per Feature, Hyphenated Kebab-Case)
|
|
993
|
+
self.register("/agent", lambda app=None, **kw: handle_agent_command(), "Enable AI Agent Mode (natural language routing)")
|
|
994
|
+
self.register("/manual", lambda app=None, **kw: handle_manual_command(), "Enable Manual Mode (direct slash commands)")
|
|
995
|
+
self.register("/help", lambda app=None, **kw: handle_help_command(), "Show full command matrix & shortcuts")
|
|
996
|
+
self.register("/batch", lambda args=None, **kw: handle_batch_command(args), "Run bulk batch scrape from .txt/.csv input file")
|
|
997
|
+
self.register("/resume-batch", lambda args=None, **kw: handle_resume_batch_command(args), "Resume an interrupted or incomplete batch from checkpoint")
|
|
998
|
+
self.register("/plugins", lambda args=None, **kw: handle_plugins_command(args), "List active plugins & interactive feature details")
|
|
999
|
+
self.register("/models", lambda args=None, **kw: handle_models_command(args), "Browse & select from curated free OpenRouter AI models")
|
|
1000
|
+
self.register("/outputs", lambda app=None, **kw: handle_outputs_command(), "View scraped videos & media folders")
|
|
1001
|
+
self.register("/new", lambda app=None, **kw: handle_new_command(), "Start a fresh new chat session (zero history)")
|
|
1002
|
+
self.register("/history", lambda app=None, **kw: handle_history_command(), "Open interactive scrollable chat history viewer (PageUp / Ctrl+U)")
|
|
1003
|
+
self.register("/clear", lambda app=None, **kw: handle_clear_command(), "Clear message history of current session & screen")
|
|
1004
|
+
self.register("/resume", lambda app=None, **kw: handle_resume_command(), "Interactive browser to resume a saved session")
|
|
1005
|
+
self.register("/delete", lambda args=None, **kw: handle_delete_command(args), "Delete saved session logs from disk")
|
|
1006
|
+
self.register("/readme", lambda app=None, **kw: handle_readme_command(), "Read project documentation in terminal")
|
|
1007
|
+
self.register("/skills", lambda app=None, **kw: handle_skills_list_command(), "List active plugin skills & trigger patterns")
|
|
1008
|
+
self.register("/doctor", handle_doctor, "Comprehensive Environment, Storage & Scraper Diagnostics")
|
|
1009
|
+
self.register("/config", lambda app=None, **kw: handle_config_command(), "View & edit global user preferences and configuration")
|
|
1010
|
+
self.register("/update", lambda app=None, **kw: handle_update_command(), "Safely pull latest updates from remote repository")
|
|
1011
|
+
self.register("/fix", lambda app=None, **kw: handle_fix_command(), "Repair & reinstall Python dependencies")
|
|
1012
|
+
self.register("/uninstall", lambda app=None, **kw: handle_uninstall_command(), "Display instructions to completely uninstall SocialScrape")
|
|
1013
|
+
self.register("/exit", lambda app=None, **kw: False, "Terminate SocialScrape session")
|
|
1014
|
+
|
|
1015
|
+
# Silent Fallback Aliases (Execution supported for convenience, NEVER shown in dropdowns)
|
|
1016
|
+
self.register("/resumebatch", lambda args=None, **kw: handle_resume_batch_command(args), is_alias=True)
|
|
1017
|
+
self.register("/resume_batch", lambda args=None, **kw: handle_resume_batch_command(args), is_alias=True)
|
|
1018
|
+
self.register("/plugin", lambda args=None, **kw: handle_plugins_command(args), is_alias=True)
|
|
1019
|
+
self.register("/model", lambda args=None, **kw: handle_models_command(args), is_alias=True)
|
|
1020
|
+
self.register("/output", lambda app=None, **kw: handle_outputs_command(), is_alias=True)
|
|
1021
|
+
self.register("/chats", lambda app=None, **kw: handle_history_command(), is_alias=True)
|
|
1022
|
+
self.register("/chat-history", lambda app=None, **kw: handle_history_command(), is_alias=True)
|
|
1023
|
+
self.register("/clean", lambda app=None, **kw: handle_clear_command(), is_alias=True)
|
|
1024
|
+
self.register("/status", handle_doctor, is_alias=True)
|
|
1025
|
+
self.register("/skill", lambda args=None, **kw: handle_skill_command(args), is_alias=True)
|
|
1026
|
+
self.register("/updates", lambda app=None, **kw: handle_update_command(), is_alias=True)
|
|
1027
|
+
self.register("/quit", lambda app=None, **kw: False, is_alias=True)
|
|
1028
|
+
|
|
1029
|
+
def register_plugin_commands(self) -> None:
|
|
1030
|
+
"""Discovers and registers commands exposed by active plugins."""
|
|
1031
|
+
for plugin in plugin_registry.list_plugins():
|
|
1032
|
+
plugin.register_commands(self)
|
|
1033
|
+
|
|
1034
|
+
def get_command_metadata(self) -> Dict[str, str]:
|
|
1035
|
+
return self._metadata
|
|
1036
|
+
|
|
1037
|
+
def dispatch(self, text: str, app: Any = None) -> bool:
|
|
1038
|
+
"""Dispatches user input to the appropriate handler. Returns False on exit."""
|
|
1039
|
+
text = text.strip()
|
|
1040
|
+
if not text:
|
|
1041
|
+
return True
|
|
1042
|
+
|
|
1043
|
+
# 1. Slash command routing
|
|
1044
|
+
if text.startswith("/"):
|
|
1045
|
+
parts = text.split(maxsplit=1)
|
|
1046
|
+
cmd = parts[0].lower()
|
|
1047
|
+
arg = parts[1] if len(parts) > 1 else ""
|
|
1048
|
+
arg_list = arg.split() if arg else []
|
|
1049
|
+
|
|
1050
|
+
if cmd in self._handlers:
|
|
1051
|
+
res = self._handlers[cmd](app=app, url=arg, args=arg_list)
|
|
1052
|
+
if res is False:
|
|
1053
|
+
return False
|
|
1054
|
+
return True
|
|
1055
|
+
else:
|
|
1056
|
+
# Check dynamic spoke folder resolution
|
|
1057
|
+
resolved = resolve_plugin_folder(cmd)
|
|
1058
|
+
if resolved:
|
|
1059
|
+
handle_plugin_command(resolved, arg_list)
|
|
1060
|
+
return True
|
|
1061
|
+
else:
|
|
1062
|
+
render_action_card(f"[bold red]Unknown command:[/bold red] {cmd}. Type [cyan]/help[/cyan] for assistance.")
|
|
1063
|
+
return True
|
|
1064
|
+
|
|
1065
|
+
# 2. Shorthand bare keywords
|
|
1066
|
+
lower_text = text.lower()
|
|
1067
|
+
if lower_text in ("clear", "cls"):
|
|
1068
|
+
handle_clear_command()
|
|
1069
|
+
return True
|
|
1070
|
+
if lower_text in ("exit", "quit"):
|
|
1071
|
+
console.print("\n[dim]Goodbye![/dim]")
|
|
1072
|
+
return False
|
|
1073
|
+
if lower_text == "help":
|
|
1074
|
+
handle_help_command()
|
|
1075
|
+
return True
|
|
1076
|
+
|
|
1077
|
+
# 3. Agent vs Manual Routing
|
|
1078
|
+
render_user_message(text)
|
|
1079
|
+
if get_agent_mode():
|
|
1080
|
+
from agent import run_openrouter_agent
|
|
1081
|
+
run_openrouter_agent(text)
|
|
1082
|
+
else:
|
|
1083
|
+
# Dynamic URL / target pattern matching across plugins
|
|
1084
|
+
matched_plugin = None
|
|
1085
|
+
for p in get_active_plugins():
|
|
1086
|
+
patterns = p.get("url_patterns", [])
|
|
1087
|
+
for pattern in patterns:
|
|
1088
|
+
if pattern.startswith("r/") or pattern.startswith("u/"):
|
|
1089
|
+
if text.startswith(pattern):
|
|
1090
|
+
matched_plugin = p
|
|
1091
|
+
break
|
|
1092
|
+
elif pattern in text:
|
|
1093
|
+
matched_plugin = p
|
|
1094
|
+
break
|
|
1095
|
+
if matched_plugin:
|
|
1096
|
+
break
|
|
1097
|
+
|
|
1098
|
+
if matched_plugin:
|
|
1099
|
+
p_display = matched_plugin.get("display_name", matched_plugin["name"].replace("-", " ").title())
|
|
1100
|
+
render_action_card(f"[dim]Detected {p_display} target. Routing to {p_display}...[/dim]")
|
|
1101
|
+
handle_plugin_command(matched_plugin["name"], [text])
|
|
1102
|
+
else:
|
|
1103
|
+
render_action_card(f"[bold yellow]Manual Mode active:[/bold yellow] '{text}'. Use slash commands (e.g. [bold cyan]/youtube[/bold cyan]) or type [bold cyan]/agent[/bold cyan] for AI mode.")
|
|
1104
|
+
|
|
1105
|
+
return True
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
router = CommandRouter()
|
|
1109
|
+
|