opencode-unlimited 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,921 @@
1
+ """
2
+ cli.py - Main Typer CLI application for opencode-unlimited.
3
+
4
+ Entry point: ocu
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ import os
12
+ import signal
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Optional
17
+
18
+ import typer
19
+ from rich import print as rprint
20
+ from rich.columns import Columns
21
+ from rich.console import Console
22
+ from rich.live import Live
23
+ from rich.panel import Panel
24
+ from rich.spinner import Spinner
25
+ from rich.syntax import Syntax
26
+ from rich.table import Table
27
+ from rich.text import Text
28
+
29
+ from opencode_unlimited import __version__
30
+ from opencode_unlimited.config import load_config, reset_config, save_config
31
+ from opencode_unlimited.constants import (
32
+ CONFIG_DIR,
33
+ DEFAULT_DASHBOARD_PORT,
34
+ DEFAULT_PROXY_PORT,
35
+ LOG_FILE,
36
+ PID_FILE,
37
+ )
38
+ from opencode_unlimited.pool.account_pool import AccountPool
39
+
40
+ console = Console()
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Top-level app
44
+ # ---------------------------------------------------------------------------
45
+
46
+ app = typer.Typer(
47
+ name="ocu",
48
+ help="OpenCode Unlimited - bypass rate limits with automatic egress rotation",
49
+ no_args_is_help=True,
50
+ rich_markup_mode="rich",
51
+ pretty_exceptions_enable=False,
52
+ )
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Sub-command groups
56
+ # ---------------------------------------------------------------------------
57
+
58
+ config_app = typer.Typer(help="Manage ocu configuration", no_args_is_help=True)
59
+ lanes_app = typer.Typer(help="Manage egress lanes", no_args_is_help=True)
60
+ accounts_app = typer.Typer(help="Manage account pool", no_args_is_help=True)
61
+ tor_app = typer.Typer(help="Check, install, and manage Tor", no_args_is_help=True)
62
+
63
+ app.add_typer(config_app, name="config")
64
+ app.add_typer(lanes_app, name="lanes")
65
+ app.add_typer(accounts_app, name="accounts")
66
+ app.add_typer(tor_app, name="tor")
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Helpers
73
+ # ---------------------------------------------------------------------------
74
+
75
+
76
+ def _setup_logging(verbose: bool = False) -> None:
77
+ """Configure logging to file + stderr if verbose."""
78
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
79
+ level = logging.DEBUG if verbose else logging.INFO
80
+ handlers: list[logging.Handler] = [
81
+ logging.FileHandler(LOG_FILE, encoding="utf-8"),
82
+ ]
83
+ if verbose:
84
+ handlers.append(logging.StreamHandler(sys.stderr))
85
+ logging.basicConfig(level=level, handlers=handlers,
86
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
87
+
88
+
89
+ def _write_pid() -> None:
90
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
91
+ PID_FILE.write_text(str(os.getpid()), encoding="utf-8")
92
+
93
+
94
+ def _delete_pid() -> None:
95
+ if PID_FILE.exists():
96
+ PID_FILE.unlink(missing_ok=True)
97
+
98
+
99
+ def _read_pid() -> Optional[int]:
100
+ if not PID_FILE.exists():
101
+ return None
102
+ try:
103
+ return int(PID_FILE.read_text(encoding="utf-8").strip())
104
+ except ValueError:
105
+ return None
106
+
107
+
108
+ def _is_running(pid: int) -> bool:
109
+ """Check whether a process with *pid* is alive (cross-platform)."""
110
+ try:
111
+ if sys.platform == "win32":
112
+ import ctypes
113
+ handle = ctypes.windll.kernel32.OpenProcess(0x0400, False, pid) # PROCESS_QUERY_INFORMATION
114
+ if handle:
115
+ ctypes.windll.kernel32.CloseHandle(handle)
116
+ return True
117
+ return False
118
+ else:
119
+ os.kill(pid, 0)
120
+ return True
121
+ except (ProcessLookupError, PermissionError, OSError):
122
+ return False
123
+
124
+
125
+ def _kill_pid(pid: int) -> None:
126
+ """Terminate a process by PID (cross-platform)."""
127
+ try:
128
+ if sys.platform == "win32":
129
+ import subprocess
130
+
131
+ # /T also kills child processes (tor.exe). TerminateProcess alone
132
+ # left Tor running after `ocu stop`.
133
+ subprocess.run(
134
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
135
+ capture_output=True,
136
+ check=False,
137
+ )
138
+ else:
139
+ os.kill(pid, signal.SIGTERM)
140
+ except (ProcessLookupError, PermissionError, OSError) as exc:
141
+ raise typer.Exit(1) from exc
142
+
143
+
144
+ def _status_panel() -> Panel:
145
+ """Build a rich panel with live proxy/account status."""
146
+ cfg = load_config()
147
+ pid = _read_pid()
148
+ running = pid is not None and _is_running(pid)
149
+
150
+ # -- proxy status grid
151
+ grid = Table.grid(expand=True, padding=(0, 2))
152
+ grid.add_column(style="dim")
153
+ grid.add_column()
154
+
155
+ grid.add_row("Proxy Running:", "[green]YES[/green]" if running else "[red]NO[/red]")
156
+ grid.add_row("PID:", str(pid) if pid else "--")
157
+ grid.add_row("Proxy Port:", str(cfg.proxy_port))
158
+ grid.add_row("WARP:", "[green]on[/green]" if cfg.enable_warp else "[dim]off[/dim]")
159
+ grid.add_row("Tor:", "[green]on[/green]" if cfg.enable_tor else "[dim]off[/dim]")
160
+ grid.add_row("Auto-Resume:", "[green]on[/green]" if cfg.auto_resume else "[dim]off[/dim]")
161
+
162
+ pool = AccountPool()
163
+ active_acc = pool.get_active()
164
+ grid.add_row("Active Account:", active_acc.id[:8] + "..." if active_acc else "[dim]none[/dim]")
165
+
166
+ return Panel(grid, title="[bold cyan]ocu status[/bold cyan]", border_style="cyan")
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # ocu start
171
+ # ---------------------------------------------------------------------------
172
+
173
+
174
+ def _run_stack_in_background_thread(cfg, dashboard: bool) -> tuple:
175
+ """Start the async proxy/guard/egress stack in a background thread."""
176
+ import threading
177
+ from opencode_unlimited.daemon import run_stack
178
+
179
+ loop_holder: dict = {}
180
+ ready = threading.Event()
181
+
182
+ def _runner() -> None:
183
+ loop = asyncio.new_event_loop()
184
+ asyncio.set_event_loop(loop)
185
+ stop_event = asyncio.Event()
186
+ loop_holder["loop"] = loop
187
+ loop_holder["stop_event"] = stop_event
188
+ ready.set()
189
+ try:
190
+ loop.run_until_complete(run_stack(cfg, dashboard=dashboard, stop_event=stop_event))
191
+ finally:
192
+ loop.close()
193
+
194
+ thread = threading.Thread(target=_runner, daemon=True)
195
+ thread.start()
196
+ ready.wait(timeout=5.0)
197
+ return thread, loop_holder
198
+
199
+
200
+ def _spawn_or_exit(spawn, proxy_port: int, **kwargs) -> int:
201
+ """Start the background daemon with a spinner; exit cleanly if it fails."""
202
+ try:
203
+ with console.status("Starting proxy stack (first Tor bootstrap can take a minute)..."):
204
+ return spawn(proxy_port, **kwargs)
205
+ except RuntimeError as exc:
206
+ console.print(f"[red]Error:[/red] {exc}")
207
+ raise typer.Exit(1) from exc
208
+
209
+
210
+ @app.command()
211
+ def start(
212
+ proxy_port: int = typer.Option(DEFAULT_PROXY_PORT, "--proxy-port", help="Local proxy port"),
213
+ no_warp: bool = typer.Option(False, "--no-warp", help="Disable WARP lane"),
214
+ no_tor: bool = typer.Option(False, "--no-tor", help="Disable Tor lane"),
215
+ dashboard: bool = typer.Option(False, "--dashboard", help="Also launch the web dashboard"),
216
+ daemon: bool = typer.Option(False, "--daemon", "-d", help="Run all proxies in the background and return"),
217
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose logging"),
218
+ ) -> None:
219
+ """Start the proxy, zen guard, and auto-resume services."""
220
+ _setup_logging(verbose)
221
+ cfg = load_config()
222
+ cfg.proxy_port = proxy_port
223
+ if no_warp:
224
+ cfg.enable_warp = False
225
+ if no_tor:
226
+ cfg.enable_tor = False
227
+ save_config(cfg)
228
+
229
+ existing_pid = _read_pid()
230
+ if existing_pid is not None and _is_running(existing_pid):
231
+ console.print(f"[yellow]ocu is already running (PID {existing_pid}).[/yellow]")
232
+ raise typer.Exit(0)
233
+
234
+ _ensure_tor(cfg)
235
+
236
+ if daemon:
237
+ from opencode_unlimited.daemon import spawn_background_daemon
238
+
239
+ pid = _spawn_or_exit(
240
+ spawn_background_daemon,
241
+ proxy_port,
242
+ no_warp=no_warp,
243
+ no_tor=no_tor,
244
+ dashboard=dashboard,
245
+ verbose=verbose,
246
+ )
247
+ console.print(Panel.fit(
248
+ f"[bold green]OpenCode Unlimited v{__version__} running in background[/bold green]\n"
249
+ f"PID: [cyan]{pid}[/cyan] Proxy: [cyan]http://127.0.0.1:{proxy_port}[/cyan]\n"
250
+ f"WARP={'on' if cfg.enable_warp else 'off'} Tor={'on' if cfg.enable_tor else 'off'}\n"
251
+ f"Run [bold]ocu run[/bold] to launch OpenCode through this proxy, or [bold]ocu stop[/bold] to stop.",
252
+ border_style="green",
253
+ ))
254
+ return
255
+
256
+ _write_pid()
257
+ console.print(Panel.fit(
258
+ f"[bold green]OpenCode Unlimited v{__version__} starting[/bold green]\n"
259
+ f"Proxy on :[cyan]{proxy_port}[/cyan] WARP={'on' if cfg.enable_warp else 'off'} "
260
+ f"Tor={'on' if cfg.enable_tor else 'off'}",
261
+ border_style="green",
262
+ ))
263
+
264
+ if dashboard:
265
+ console.print(
266
+ f"[dim]Dashboard running at [link]http://localhost:{cfg.dashboard_port}[/link][/dim]"
267
+ )
268
+
269
+ thread, loop_holder = _run_stack_in_background_thread(cfg, dashboard=dashboard)
270
+
271
+ # Live status loop
272
+ try:
273
+ with Live(console=console, refresh_per_second=1) as live:
274
+ while thread.is_alive():
275
+ live.update(_status_panel())
276
+ time.sleep(1)
277
+ except KeyboardInterrupt:
278
+ pass
279
+ finally:
280
+ loop = loop_holder.get("loop")
281
+ stop_event = loop_holder.get("stop_event")
282
+ if loop is not None and stop_event is not None and not loop.is_closed():
283
+ loop.call_soon_threadsafe(stop_event.set)
284
+ thread.join(timeout=5.0)
285
+ _delete_pid()
286
+ console.print("\n[bold yellow]Stopped.[/bold yellow]")
287
+
288
+
289
+ @app.command("_serve", hidden=True)
290
+ def _serve(
291
+ proxy_port: int = typer.Option(DEFAULT_PROXY_PORT, "--proxy-port"),
292
+ no_warp: bool = typer.Option(False, "--no-warp"),
293
+ no_tor: bool = typer.Option(False, "--no-tor"),
294
+ dashboard: bool = typer.Option(False, "--dashboard"),
295
+ verbose: bool = typer.Option(False, "--verbose", "-v"),
296
+ ) -> None:
297
+ """Internal background daemon entrypoint."""
298
+ from opencode_unlimited.daemon import run_stack
299
+
300
+ _setup_logging(verbose)
301
+ cfg = load_config()
302
+ cfg.proxy_port = proxy_port
303
+ if no_warp:
304
+ cfg.enable_warp = False
305
+ if no_tor:
306
+ cfg.enable_tor = False
307
+ save_config(cfg)
308
+
309
+ _write_pid()
310
+ try:
311
+ asyncio.run(run_stack(cfg, dashboard=dashboard))
312
+ except KeyboardInterrupt:
313
+ pass
314
+ finally:
315
+ _delete_pid()
316
+
317
+
318
+ # ---------------------------------------------------------------------------
319
+ # ocu run / ocu open
320
+ # ---------------------------------------------------------------------------
321
+
322
+
323
+ @app.command("setup")
324
+ def setup_opencode() -> None:
325
+ """Detect installed OpenCode (CLI / Desktop) and interactively install or configure it."""
326
+ from opencode_unlimited.launcher import (
327
+ detect_opencode,
328
+ print_detection_table,
329
+ prompt_and_install_opencode,
330
+ )
331
+
332
+ cfg = load_config()
333
+ detected = detect_opencode(cfg)
334
+ print_detection_table(detected)
335
+
336
+ if detected["cli"] or detected["desktop"]:
337
+ if not typer.confirm("OpenCode is already detected. Re-run installer / change path?", default=False):
338
+ return
339
+
340
+ prompt_and_install_opencode(cfg, save_config, prefer_desktop=False)
341
+
342
+
343
+ @app.command("run")
344
+ def run_opencode(
345
+ opencode_args: Optional[list[str]] = typer.Argument(
346
+ None,
347
+ help="Extra arguments forwarded to OpenCode (use -- before flags)",
348
+ ),
349
+ desktop: bool = typer.Option(False, "--desktop", help="Launch OpenCode Desktop instead of CLI"),
350
+ proxy_port: int = typer.Option(DEFAULT_PROXY_PORT, "--proxy-port", help="Local proxy port"),
351
+ no_warp: bool = typer.Option(False, "--no-warp", help="Disable WARP lane"),
352
+ no_tor: bool = typer.Option(False, "--no-tor", help="Disable Tor lane"),
353
+ dashboard: bool = typer.Option(False, "--dashboard", help="Also launch the web dashboard"),
354
+ stop_on_exit: bool = typer.Option(False, "--stop-on-exit", help="Stop background proxy when OpenCode exits"),
355
+ ) -> None:
356
+ """Detect/install OpenCode if needed, start proxies in background, and launch OpenCode."""
357
+ from opencode_unlimited.daemon import is_port_open, spawn_background_daemon
358
+ from opencode_unlimited.launcher import launch_opencode, prompt_and_install_opencode
359
+
360
+ cfg = load_config()
361
+ cfg.proxy_port = proxy_port
362
+ if no_warp:
363
+ cfg.enable_warp = False
364
+ if no_tor:
365
+ cfg.enable_tor = False
366
+ save_config(cfg)
367
+
368
+ use_desktop = prompt_and_install_opencode(cfg, save_config, prefer_desktop=desktop)
369
+ if use_desktop is None:
370
+ console.print("[yellow]Aborted.[/yellow]")
371
+ raise typer.Exit(1)
372
+
373
+ _ensure_tor(cfg)
374
+
375
+ started_here = False
376
+ existing_pid = _read_pid()
377
+ if existing_pid is None or not _is_running(existing_pid) or not is_port_open("127.0.0.1", proxy_port):
378
+ console.print(f"[cyan]Starting ocu proxy stack in background on 127.0.0.1:{proxy_port}...[/cyan]")
379
+ _spawn_or_exit(
380
+ spawn_background_daemon,
381
+ proxy_port,
382
+ no_warp=no_warp,
383
+ no_tor=no_tor,
384
+ dashboard=dashboard,
385
+ )
386
+ started_here = True
387
+ else:
388
+ console.print(f"[dim]Using running ocu proxy on 127.0.0.1:{proxy_port} (PID {existing_pid})[/dim]")
389
+
390
+ try:
391
+ exit_code = launch_opencode(
392
+ proxy_port,
393
+ extra_args=list(opencode_args or []),
394
+ desktop=use_desktop,
395
+ cfg=cfg,
396
+ )
397
+ except FileNotFoundError as exc:
398
+ console.print(f"[red]Error:[/red] {exc}")
399
+ raise typer.Exit(1)
400
+ finally:
401
+ if stop_on_exit and started_here:
402
+ pid = _read_pid()
403
+ if pid is not None and _is_running(pid):
404
+ _kill_pid(pid)
405
+ _delete_pid()
406
+ console.print("[yellow]Stopped background ocu proxy.[/yellow]")
407
+
408
+ if exit_code != 0:
409
+ raise typer.Exit(exit_code)
410
+
411
+
412
+ # ---------------------------------------------------------------------------
413
+ # ocu stop
414
+ # ---------------------------------------------------------------------------
415
+
416
+
417
+ @app.command()
418
+ def stop() -> None:
419
+ """Kill the running ocu proxy process."""
420
+ pid = _read_pid()
421
+ if pid is None:
422
+ console.print("[yellow]ocu is not running (no PID file found).[/yellow]")
423
+ raise typer.Exit(0)
424
+ if not _is_running(pid):
425
+ console.print(f"[yellow]PID {pid} is not alive. Cleaning up PID file.[/yellow]")
426
+ _delete_pid()
427
+ raise typer.Exit(0)
428
+ _kill_pid(pid)
429
+ _delete_pid()
430
+ console.print(f"[green]Stopped ocu (PID {pid}).[/green]")
431
+
432
+
433
+ # ---------------------------------------------------------------------------
434
+ # ocu status
435
+ # ---------------------------------------------------------------------------
436
+
437
+
438
+ @app.command()
439
+ def status() -> None:
440
+ """Show proxy status, lane health, and active account."""
441
+ console.print(_status_panel())
442
+
443
+ # Lane table
444
+ try:
445
+ from opencode_unlimited.proxy.proxy_chain import ProxyChain
446
+ cfg = load_config()
447
+ pc = ProxyChain(cfg)
448
+ console.print(pc.status_table())
449
+ except Exception as exc:
450
+ console.print(f"[dim]Lane info unavailable: {exc}[/dim]")
451
+
452
+ # Account table
453
+ try:
454
+ pool = AccountPool()
455
+ console.print(pool.status_table())
456
+ except Exception as exc:
457
+ console.print(f"[dim]Account pool unavailable: {exc}[/dim]")
458
+
459
+
460
+ # ---------------------------------------------------------------------------
461
+ # ocu config
462
+ # ---------------------------------------------------------------------------
463
+
464
+
465
+ @config_app.command("show")
466
+ def config_show() -> None:
467
+ """Pretty-print current configuration."""
468
+ cfg = load_config()
469
+ table = Table(title="ocu Configuration", show_lines=True)
470
+ table.add_column("Key", style="cyan")
471
+ table.add_column("Value")
472
+
473
+ for key, val in cfg.model_dump().items():
474
+ table.add_row(key, str(val))
475
+
476
+ console.print(table)
477
+
478
+
479
+ def _parse_list(value: str) -> list[str]:
480
+ """Parse '["a","b"]' or 'a,b' into a list of strings."""
481
+ import json
482
+
483
+ text = value.strip()
484
+ if text.startswith("["):
485
+ parsed = json.loads(text)
486
+ if not isinstance(parsed, list):
487
+ raise ValueError("expected a JSON list")
488
+ return [str(v) for v in parsed]
489
+ return [part.strip() for part in text.split(",") if part.strip()]
490
+
491
+
492
+ @config_app.command("set")
493
+ def config_set(
494
+ key: str = typer.Argument(..., help="Config key to update"),
495
+ value: str = typer.Argument(..., help="New value"),
496
+ ) -> None:
497
+ """Update a single config key."""
498
+ cfg = load_config()
499
+ if not hasattr(cfg, key):
500
+ console.print(f"[red]Unknown config key:[/red] {key!r}")
501
+ raise typer.Exit(1)
502
+
503
+ # OCUConfig.__setattr__ validates and coerces ports/bools/log level.
504
+ # Lists (lanes_priority) are accepted as JSON or comma-separated text.
505
+ try:
506
+ coerced: object = value
507
+ if isinstance(getattr(cfg, key), list):
508
+ coerced = _parse_list(value)
509
+ setattr(cfg, key, coerced)
510
+ coerced = getattr(cfg, key)
511
+ except (ValueError, TypeError) as exc:
512
+ console.print(f"[red]Invalid value:[/red] {exc}")
513
+ raise typer.Exit(1)
514
+
515
+ save_config(cfg)
516
+ console.print(f"[green]Set[/green] [cyan]{key}[/cyan] = {coerced!r}")
517
+
518
+
519
+ @config_app.command("reset")
520
+ def config_reset() -> None:
521
+ """Reset configuration to built-in defaults."""
522
+ reset_config()
523
+ console.print("[green]Configuration reset to defaults.[/green]")
524
+
525
+
526
+ # ---------------------------------------------------------------------------
527
+ # ocu lanes
528
+ # ---------------------------------------------------------------------------
529
+
530
+
531
+ @lanes_app.command("list")
532
+ def lanes_list() -> None:
533
+ """List all egress lanes and their health status."""
534
+ try:
535
+ from opencode_unlimited.proxy.proxy_chain import ProxyChain
536
+ cfg = load_config()
537
+ pc = ProxyChain(cfg)
538
+ console.print(pc.status_table())
539
+ except Exception as exc:
540
+ console.print(f"[red]Error:[/red] {exc}")
541
+ raise typer.Exit(1)
542
+
543
+
544
+ @lanes_app.command("rotate")
545
+ def lanes_rotate() -> None:
546
+ """Force an immediate egress lane rotation."""
547
+ try:
548
+ from opencode_unlimited.proxy.proxy_chain import ProxyChain
549
+ cfg = load_config()
550
+ pc = ProxyChain(cfg)
551
+ new_lane = pc.rotate()
552
+ console.print(f"[green]Rotated to lane:[/green] [cyan]{new_lane.value}[/cyan]")
553
+ except Exception as exc:
554
+ console.print(f"[red]Error:[/red] {exc}")
555
+ raise typer.Exit(1)
556
+
557
+
558
+ @lanes_app.command("warp")
559
+ def lanes_warp(
560
+ state: str = typer.Argument(..., help="on or off"),
561
+ ) -> None:
562
+ """Enable or disable the WARP lane."""
563
+ if state.lower() not in ("on", "off"):
564
+ console.print("[red]State must be 'on' or 'off'.[/red]")
565
+ raise typer.Exit(1)
566
+ cfg = load_config()
567
+ cfg.enable_warp = state.lower() == "on"
568
+ save_config(cfg)
569
+ console.print(f"WARP lane: [{'green' if cfg.enable_warp else 'dim'}]{state.upper()}[/{'green' if cfg.enable_warp else 'dim'}]")
570
+
571
+
572
+ @lanes_app.command("tor")
573
+ def lanes_tor(
574
+ state: str = typer.Argument(..., help="on or off"),
575
+ ) -> None:
576
+ """Enable or disable the Tor lane."""
577
+ if state.lower() not in ("on", "off"):
578
+ console.print("[red]State must be 'on' or 'off'.[/red]")
579
+ raise typer.Exit(1)
580
+ cfg = load_config()
581
+ cfg.enable_tor = state.lower() == "on"
582
+ save_config(cfg)
583
+ console.print(f"Tor lane: [{'green' if cfg.enable_tor else 'dim'}]{state.upper()}[/{'green' if cfg.enable_tor else 'dim'}]")
584
+
585
+
586
+ # ---------------------------------------------------------------------------
587
+ # ocu logs
588
+ # ---------------------------------------------------------------------------
589
+
590
+
591
+ @app.command()
592
+ def logs(
593
+ follow: bool = typer.Option(False, "--follow", "-f", help="Tail log output"),
594
+ lines: int = typer.Option(50, "--lines", "-n", help="Number of lines to show"),
595
+ ) -> None:
596
+ """Display or tail the ocu log file."""
597
+ if not LOG_FILE.exists():
598
+ console.print("[yellow]Log file not found. Has ocu been started yet?[/yellow]")
599
+ raise typer.Exit(0)
600
+
601
+ def _tail(n: int) -> list[str]:
602
+ text = LOG_FILE.read_text(encoding="utf-8", errors="replace")
603
+ return text.splitlines()[-n:]
604
+
605
+ if not follow:
606
+ content = "\n".join(_tail(lines))
607
+ console.print(Syntax(content, "log", theme="monokai", line_numbers=True))
608
+ return
609
+
610
+ try:
611
+ with open(LOG_FILE, encoding="utf-8", errors="replace") as fh:
612
+ # Seek to tail position
613
+ fh.seek(0, 2)
614
+ pos = max(0, fh.tell() - 8192)
615
+ fh.seek(pos)
616
+ # Print last N lines
617
+ buf = fh.read().splitlines()
618
+ for line in buf[-lines:]:
619
+ console.print(line)
620
+ # Follow new lines
621
+ while True:
622
+ line = fh.readline()
623
+ if line:
624
+ console.print(line.rstrip())
625
+ else:
626
+ time.sleep(0.25)
627
+ except KeyboardInterrupt:
628
+ console.print("\n[bold yellow]Stopped following logs.[/bold yellow]")
629
+
630
+
631
+ # ---------------------------------------------------------------------------
632
+ # ocu accounts
633
+ # ---------------------------------------------------------------------------
634
+
635
+
636
+ @accounts_app.command("list")
637
+ def accounts_list() -> None:
638
+ """Display the account pool."""
639
+ pool = AccountPool()
640
+ console.print(pool.status_table())
641
+
642
+
643
+ @accounts_app.command("add")
644
+ def accounts_add(
645
+ token: str = typer.Argument(..., help="Account token to add"),
646
+ ) -> None:
647
+ """Add a new account token to the pool."""
648
+ pool = AccountPool()
649
+ acc = pool.add_account(token)
650
+ console.print(f"[green]Added account[/green] [cyan]{acc.id}[/cyan]")
651
+
652
+
653
+ @accounts_app.command("remove")
654
+ def accounts_remove(
655
+ account_id: str = typer.Argument(..., help="Account ID to remove"),
656
+ ) -> None:
657
+ """Remove an account from the pool by ID."""
658
+ pool = AccountPool()
659
+ try:
660
+ pool.remove_account(account_id)
661
+ console.print(f"[green]Removed account[/green] [cyan]{account_id}[/cyan]")
662
+ except ValueError as exc:
663
+ console.print(f"[red]Error:[/red] {exc}")
664
+ raise typer.Exit(1)
665
+
666
+
667
+ @accounts_app.command("rotate")
668
+ def accounts_rotate() -> None:
669
+ """Manually rotate to the next available account."""
670
+ pool = AccountPool()
671
+ new_acc = pool.rotate()
672
+ if new_acc:
673
+ console.print(f"[green]Rotated to account[/green] [cyan]{new_acc.id}[/cyan]")
674
+ else:
675
+ console.print("[red]No healthy accounts available to rotate to.[/red]")
676
+ raise typer.Exit(1)
677
+
678
+
679
+ # ---------------------------------------------------------------------------
680
+ # ocu dashboard
681
+ # ---------------------------------------------------------------------------
682
+
683
+
684
+ @app.command()
685
+ def dashboard(
686
+ port: int = typer.Option(DEFAULT_DASHBOARD_PORT, "--port", "-p", help="Dashboard port"),
687
+ ) -> None:
688
+ """Launch the web dashboard."""
689
+ try:
690
+ from opencode_unlimited.dashboard.server import create_app, run_dashboard
691
+ from opencode_unlimited.proxy.proxy_chain import ProxyChain
692
+ except ImportError as exc:
693
+ console.print(f"[red]Import error:[/red] {exc}\nInstall extras: pip install opencode-unlimited[dashboard]")
694
+ raise typer.Exit(1)
695
+
696
+ cfg = load_config()
697
+ proxy_chain = ProxyChain(cfg)
698
+ account_pool = AccountPool()
699
+ dash_app = create_app(proxy_chain, None, account_pool, cfg)
700
+
701
+ console.print(Panel.fit(
702
+ f"Dashboard running at [link]http://localhost:{port}[/link]\nPress [bold]Ctrl+C[/bold] to stop.",
703
+ title="[cyan]ocu dashboard[/cyan]",
704
+ border_style="cyan",
705
+ ))
706
+ try:
707
+ run_dashboard(dash_app, port)
708
+ except KeyboardInterrupt:
709
+ console.print("\n[bold yellow]Dashboard stopped.[/bold yellow]")
710
+
711
+
712
+ # ---------------------------------------------------------------------------
713
+ # ocu tor
714
+ # ---------------------------------------------------------------------------
715
+
716
+
717
+ def _ensure_tor(cfg) -> None:
718
+ """
719
+ If the Tor lane is enabled but Tor isn't installed, offer to install it.
720
+ Only prompts in an interactive terminal; otherwise the daemon simply runs
721
+ without the Tor lane.
722
+ """
723
+ if not cfg.enable_tor:
724
+ return
725
+ from opencode_unlimited.egress.tor_installer import find_tor_binary
726
+
727
+ if find_tor_binary() is not None:
728
+ return
729
+ if not sys.stdin.isatty():
730
+ console.print("[dim]Tor not installed; continuing without the Tor lane.[/dim]")
731
+ return
732
+ console.print("[yellow]Tor is enabled but not installed.[/yellow]")
733
+ if typer.confirm("Install Tor now?", default=True):
734
+ if _install_tor_interactive(assume_yes=False, add_path=True):
735
+ return
736
+ console.print(
737
+ "[dim]Continuing without the Tor lane. Run [bold]ocu tor install[/bold] later, "
738
+ "or [bold]ocu lanes tor off[/bold] to stop this prompt.[/dim]"
739
+ )
740
+
741
+
742
+ def _install_tor_interactive(*, assume_yes: bool, add_path: bool) -> bool:
743
+ """Install Tor with the best method for this OS. Returns True if tor is usable afterwards."""
744
+ import subprocess
745
+
746
+ from opencode_unlimited.egress import tor_installer as ti
747
+
748
+ options = ti.package_manager_options()
749
+ if options:
750
+ console.print("\n[bold cyan]Tor install options:[/bold cyan]")
751
+ for i, (label, _) in enumerate(options, 1):
752
+ console.print(f" [bold]{i}.[/bold] {label}")
753
+ bundle_idx = len(options) + 1
754
+ console.print(f" [bold]{bundle_idx}.[/bold] Official Tor Expert Bundle (no root, into {ti.INSTALL_DIR})")
755
+ choice = "1" if assume_yes else typer.prompt("Select install method", default="1")
756
+ try:
757
+ idx = int(choice)
758
+ except ValueError:
759
+ idx = -1
760
+ if 1 <= idx <= len(options):
761
+ label, cmd = options[idx - 1]
762
+ console.print(f"[cyan]Running:[/cyan] {' '.join(cmd)}")
763
+ rc = subprocess.run(cmd).returncode
764
+ if rc != 0:
765
+ console.print(f"[red]Installer exited with code {rc}.[/red]")
766
+ return False
767
+ found = ti.find_tor_binary()
768
+ if found:
769
+ console.print(f"[green]Tor installed:[/green] {found}")
770
+ return found is not None
771
+ if idx != bundle_idx:
772
+ console.print("[red]Invalid selection.[/red]")
773
+ return False
774
+
775
+ plat = ti.bundle_platform()
776
+ if plat is None:
777
+ console.print("[red]No official Tor bundle for this platform. Install Tor with your package manager.[/red]")
778
+ return False
779
+ if not assume_yes and not typer.confirm(
780
+ f"Download the official Tor Expert Bundle ({plat}) from dist.torproject.org into {ti.INSTALL_DIR}?",
781
+ default=True,
782
+ ):
783
+ return False
784
+
785
+ from rich.progress import BarColumn, DownloadColumn, Progress, TransferSpeedColumn
786
+
787
+ try:
788
+ with Progress(
789
+ "[progress.description]{task.description}", BarColumn(), DownloadColumn(),
790
+ TransferSpeedColumn(), console=console, transient=True,
791
+ ) as prog:
792
+ task = prog.add_task("Downloading Tor", total=None)
793
+ binary = ti.install_tor_bundle(
794
+ progress=lambda done, total: prog.update(task, completed=done, total=total)
795
+ )
796
+ except Exception as exc: # noqa: BLE001
797
+ console.print(f"[red]Tor install failed:[/red] {exc}")
798
+ return False
799
+
800
+ version = ti.tor_version(str(binary)) or "unknown version"
801
+ console.print(f"[green]Installed[/green] {version} at [cyan]{binary}[/cyan] (SHA-256 verified)")
802
+
803
+ if add_path:
804
+ _offer_add_to_path(binary.parent, assume_yes=assume_yes)
805
+ return True
806
+
807
+
808
+ def _offer_add_to_path(directory: Path, *, assume_yes: bool) -> None:
809
+ from opencode_unlimited.egress import tor_installer as ti
810
+
811
+ if sys.platform != "win32":
812
+ if not ti.path_contains(os.environ.get("PATH", ""), str(directory)):
813
+ console.print(
814
+ f"[dim]To use `tor` directly, add this to your shell profile:[/dim]\n"
815
+ f' export PATH="$PATH:{directory}"'
816
+ )
817
+ return
818
+ if ti.user_path_has(directory):
819
+ console.print(f"[dim]{directory} is already on your PATH.[/dim]")
820
+ return
821
+ if not assume_yes and not typer.confirm(f"Add {directory} to your user PATH?", default=True):
822
+ console.print("[dim]Skipped. ocu still finds Tor there without PATH.[/dim]")
823
+ return
824
+ try:
825
+ ti.add_to_user_path(directory)
826
+ except Exception as exc: # noqa: BLE001
827
+ console.print(f"[red]Could not update PATH:[/red] {exc}")
828
+ return
829
+ console.print(
830
+ f"[green]Added to user PATH:[/green] {directory}\n"
831
+ "[dim]Open a new terminal for `tor` to be available there.[/dim]"
832
+ )
833
+
834
+
835
+ @tor_app.command("status")
836
+ def tor_status() -> None:
837
+ """Show whether Tor is installed, on PATH, and listening."""
838
+ from opencode_unlimited.constants import TOR_SOCKS_PORT
839
+ from opencode_unlimited.daemon import is_port_open
840
+ from opencode_unlimited.egress import tor_installer as ti
841
+
842
+ binary = ti.find_tor_binary()
843
+ grid = Table.grid(padding=(0, 2))
844
+ grid.add_column(style="dim")
845
+ grid.add_column()
846
+ grid.add_row("Installed:", "[green]yes[/green]" if binary else "[red]no[/red] (run [bold]ocu tor install[/bold])")
847
+ if binary:
848
+ grid.add_row("Binary:", binary)
849
+ grid.add_row("Version:", ti.tor_version(binary) or "[dim]unknown[/dim]")
850
+ on_path = ti.user_path_has(Path(binary).parent)
851
+ grid.add_row("On PATH:", "[green]yes[/green]" if on_path else "[yellow]no[/yellow] (run [bold]ocu tor path[/bold])")
852
+ listening = is_port_open("127.0.0.1", TOR_SOCKS_PORT)
853
+ grid.add_row(f"SOCKS :{TOR_SOCKS_PORT}:", "[green]listening[/green]" if listening else "[dim]not listening[/dim]")
854
+ grid.add_row("Tor lane:", "[green]on[/green]" if load_config().enable_tor else "[dim]off[/dim]")
855
+ console.print(Panel(grid, title="[bold cyan]Tor[/bold cyan]", border_style="cyan"))
856
+
857
+
858
+ @tor_app.command("install")
859
+ def tor_install(
860
+ yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),
861
+ no_path: bool = typer.Option(False, "--no-path", help="Don't add Tor to PATH"),
862
+ force: bool = typer.Option(False, "--force", help="Reinstall even if Tor is found"),
863
+ ) -> None:
864
+ """Install Tor (official bundle on Windows, package manager elsewhere) and add it to PATH."""
865
+ from opencode_unlimited.egress import tor_installer as ti
866
+
867
+ existing = ti.find_tor_binary()
868
+ if existing and not force:
869
+ console.print(f"[green]Tor is already installed:[/green] {existing}")
870
+ if not no_path:
871
+ _offer_add_to_path(Path(existing).parent, assume_yes=yes)
872
+ return
873
+ if not _install_tor_interactive(assume_yes=yes, add_path=not no_path):
874
+ raise typer.Exit(1)
875
+
876
+
877
+ @tor_app.command("path")
878
+ def tor_path(
879
+ yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),
880
+ ) -> None:
881
+ """Add the installed Tor's folder to your user PATH (Windows)."""
882
+ from opencode_unlimited.egress import tor_installer as ti
883
+
884
+ binary = ti.find_tor_binary()
885
+ if binary is None:
886
+ console.print("[red]Tor is not installed.[/red] Run [bold]ocu tor install[/bold].")
887
+ raise typer.Exit(1)
888
+ _offer_add_to_path(Path(binary).parent, assume_yes=yes)
889
+
890
+
891
+ @tor_app.command("renew")
892
+ def tor_renew() -> None:
893
+ """Ask the running Tor for a new circuit (new exit IP)."""
894
+ from opencode_unlimited.egress.tor_manager import TorManager
895
+
896
+ tm = TorManager()
897
+ if asyncio.run(tm.new_identity()):
898
+ console.print("[green]New Tor identity requested.[/green]")
899
+ else:
900
+ console.print("[red]Could not reach the Tor control port. Is ocu running with Tor?[/red]")
901
+ raise typer.Exit(1)
902
+
903
+
904
+ # ---------------------------------------------------------------------------
905
+ # ocu version
906
+ # ---------------------------------------------------------------------------
907
+
908
+
909
+ @app.command()
910
+ def version() -> None:
911
+ """Show the installed version of opencode-unlimited."""
912
+ console.print(f"opencode-unlimited [cyan]v{__version__}[/cyan]")
913
+
914
+
915
+ # ---------------------------------------------------------------------------
916
+ # Entry point
917
+ # ---------------------------------------------------------------------------
918
+
919
+
920
+ if __name__ == "__main__":
921
+ app()