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,372 @@
1
+ """
2
+ tor_manager.py - Tor daemon manager for opencode-unlimited.
3
+
4
+ Starts/stops a Tor subprocess and rotates circuits via stem.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ import os
12
+ import re
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Optional
16
+
17
+ from rich.console import Console
18
+
19
+ from ..constants import CONFIG_DIR
20
+ from .tor_installer import find_tor_binary
21
+
22
+ # No logging.basicConfig here: configuring the root logger at import time
23
+ # overrode the CLI's file logging. The application configures logging.
24
+ log = logging.getLogger(__name__)
25
+ console = Console()
26
+
27
+ TOR_DATA_DIR: Path = CONFIG_DIR / "tor-data"
28
+ """Persistent Tor DataDirectory. Keeping the cached consensus makes restarts bootstrap faster."""
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Constants
32
+ # ---------------------------------------------------------------------------
33
+
34
+ # Seconds to wait after NEWNYM before circuits are rebuilt
35
+ _NEWNYM_PAUSE: float = 5.0
36
+
37
+ # Bootstrap fails if no new "Bootstrapped N%" progress appears for this long.
38
+ # A cold start (empty DataDirectory) can take well over a minute on slow
39
+ # networks, so this is a stall timeout rather than a total timeout.
40
+ _BOOTSTRAP_TIMEOUT: float = 90.0
41
+ # Hard cap on total bootstrap time.
42
+ _BOOTSTRAP_MAX: float = 300.0
43
+ _BOOTSTRAP_RE = re.compile(r"Bootstrapped (\d+)%")
44
+ _BOOTSTRAP_POLL: float = 2.0
45
+
46
+ # Tor check URL (fetched through the SOCKS proxy)
47
+ _IP_CHECK_URL = "https://check.torproject.org/api/ip"
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # TorManager
52
+ # ---------------------------------------------------------------------------
53
+
54
+ class TorManager:
55
+ """
56
+ Manages a Tor daemon subprocess, exposing a SOCKS5 proxy locally.
57
+
58
+ Usage::
59
+
60
+ manager = TorManager(socks_port=9050, control_port=9051)
61
+ await manager.start()
62
+ url = manager.get_socks_url() # socks5://127.0.0.1:9050
63
+ await manager.new_identity()
64
+ await manager.stop()
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ socks_port: int = 9050,
70
+ control_port: int = 9051,
71
+ control_password: str = "",
72
+ data_dir: Path = TOR_DATA_DIR,
73
+ ) -> None:
74
+ self.socks_port = socks_port
75
+ self.control_port = control_port
76
+ self.control_password = control_password
77
+
78
+ self._binary: Optional[str] = find_tor_binary()
79
+ self._process: Optional[asyncio.subprocess.Process] = None
80
+ self._torrc_path: Optional[Path] = None
81
+ self._data_dir: Path = data_dir
82
+ self._drain_task: Optional[asyncio.Task] = None
83
+ self.external = False # True when reusing a Tor we didn't start
84
+
85
+ log.debug(
86
+ "TorManager init (socks=%d, control=%d, binary=%s)",
87
+ socks_port, control_port, self._binary,
88
+ )
89
+
90
+ # ------------------------------------------------------------------
91
+ # Public helpers
92
+ # ------------------------------------------------------------------
93
+
94
+ @property
95
+ def binary(self) -> Optional[str]:
96
+ return self._binary
97
+
98
+ def is_tor_available(self) -> bool:
99
+ """Return True if a tor binary was found (PATH, ocu's bundle, or Tor Browser)."""
100
+ if self._binary is None:
101
+ self._binary = find_tor_binary()
102
+ log.debug("tor binary: %s", self._binary)
103
+ return self._binary is not None
104
+
105
+ async def _socks_is_listening(self) -> bool:
106
+ """True if something on socks_port answers a SOCKS5 greeting."""
107
+ try:
108
+ reader, writer = await asyncio.wait_for(
109
+ asyncio.open_connection("127.0.0.1", self.socks_port), 2.0
110
+ )
111
+ except (OSError, asyncio.TimeoutError):
112
+ return False
113
+ try:
114
+ writer.write(b"\x05\x01\x00")
115
+ await writer.drain()
116
+ reply = await asyncio.wait_for(reader.readexactly(2), 2.0)
117
+ return reply == b"\x05\x00"
118
+ except (OSError, asyncio.TimeoutError, asyncio.IncompleteReadError):
119
+ return False
120
+ finally:
121
+ writer.close()
122
+
123
+ def get_socks_url(self) -> str:
124
+ """Return the local SOCKS5 URL for this Tor instance."""
125
+ return f"socks5://127.0.0.1:{self.socks_port}"
126
+
127
+ # ------------------------------------------------------------------
128
+ # Lifecycle
129
+ # ------------------------------------------------------------------
130
+
131
+ async def start(self) -> bool:
132
+ """
133
+ Start a Tor subprocess with a temporary torrc.
134
+
135
+ Writes a minimal torrc to a temp directory, launches `tor -f <torrc>`,
136
+ and waits for the bootstrap-complete log line.
137
+
138
+ If a SOCKS5 server already answers on ``socks_port`` (a system Tor
139
+ service or Tor Browser), it is reused instead of starting a second
140
+ Tor that would fail to bind the port.
141
+
142
+ Returns True when Tor is bootstrapped and ready.
143
+ """
144
+ if self._process is not None and self._process.returncode is None:
145
+ log.warning("Tor already running (pid=%d)", self._process.pid)
146
+ return True
147
+
148
+ if await self._socks_is_listening():
149
+ log.info("Reusing existing SOCKS5 proxy on 127.0.0.1:%d", self.socks_port)
150
+ self.external = True
151
+ return True
152
+
153
+ if not self.is_tor_available():
154
+ log.error("Tor binary not found. Install it with `ocu tor install`.")
155
+ return False
156
+
157
+ self._data_dir.mkdir(parents=True, exist_ok=True)
158
+ self._torrc_path = self._data_dir / "torrc"
159
+ torrc_content = _build_torrc(
160
+ data_dir=self._data_dir,
161
+ socks_port=self.socks_port,
162
+ control_port=self.control_port,
163
+ geoip_dir=_geoip_dir(Path(self._binary)), # type: ignore[arg-type]
164
+ )
165
+ self._torrc_path.write_text(torrc_content, encoding="utf-8")
166
+ log.debug("torrc written to %s:\n%s", self._torrc_path, torrc_content)
167
+
168
+ log.info("Starting Tor: %s", self._binary)
169
+ self._process = await asyncio.create_subprocess_exec(
170
+ self._binary, # type: ignore[arg-type]
171
+ "-f", str(self._torrc_path),
172
+ stdout=asyncio.subprocess.PIPE,
173
+ stderr=asyncio.subprocess.STDOUT,
174
+ )
175
+
176
+ bootstrapped = await self._wait_for_bootstrap()
177
+ if bootstrapped:
178
+ # Keep reading Tor's stdout. If nobody drains the pipe, Tor
179
+ # blocks on its next log write once the OS buffer fills.
180
+ self._drain_task = asyncio.create_task(self._drain_stdout())
181
+ log.info(
182
+ "Tor ready on %s, control :%d (pid=%d)",
183
+ self.get_socks_url(), self.control_port, self._process.pid,
184
+ )
185
+ else:
186
+ log.error("Tor bootstrap failed or timed out; stopping it.")
187
+ await self.stop()
188
+ return bootstrapped
189
+
190
+ async def _drain_stdout(self) -> None:
191
+ proc = self._process
192
+ if proc is None or proc.stdout is None:
193
+ return
194
+ try:
195
+ while line := await proc.stdout.readline():
196
+ log.debug("[tor] %s", line.decode(errors="replace").rstrip())
197
+ except (asyncio.CancelledError, OSError):
198
+ pass
199
+
200
+ async def stop(self) -> None:
201
+ """Kill the Tor subprocess we started (an external Tor is left alone)."""
202
+ if self._drain_task is not None:
203
+ self._drain_task.cancel()
204
+ self._drain_task = None
205
+ if self._process is not None:
206
+ try:
207
+ self._process.kill()
208
+ await self._process.wait()
209
+ log.info("Process terminated")
210
+ except ProcessLookupError:
211
+ pass
212
+ finally:
213
+ self._process = None
214
+
215
+ # ------------------------------------------------------------------
216
+ # Circuit management
217
+ # ------------------------------------------------------------------
218
+
219
+ async def new_identity(self) -> bool:
220
+ """
221
+ Send SIGNAL NEWNYM to the Tor control port and wait for the
222
+ new circuit to be established.
223
+
224
+ Uses stem.control.Controller in a thread executor because stem
225
+ is synchronous.
226
+
227
+ Returns True on success.
228
+ """
229
+ try:
230
+ loop = asyncio.get_event_loop()
231
+ await loop.run_in_executor(None, self._sync_new_identity)
232
+ # Give Tor time to build fresh circuits
233
+ log.info("Waiting %.0fs for new circuits...", _NEWNYM_PAUSE)
234
+ await asyncio.sleep(_NEWNYM_PAUSE)
235
+ log.info("New identity ready")
236
+ return True
237
+ except Exception as exc: # noqa: BLE001
238
+ log.error("new_identity failed: %s", exc)
239
+ return False
240
+
241
+ def _sync_new_identity(self) -> None:
242
+ """Synchronous stem call -- run in executor to avoid blocking the loop."""
243
+ try:
244
+ from stem.control import Controller # type: ignore[import-untyped]
245
+ except ImportError as exc:
246
+ raise RuntimeError("stem library not installed: pip install stem") from exc
247
+
248
+ with Controller.from_port(port=self.control_port) as ctrl:
249
+ if self.control_password:
250
+ ctrl.authenticate(password=self.control_password)
251
+ else:
252
+ ctrl.authenticate()
253
+ ctrl.signal("NEWNYM")
254
+ log.debug("SIGNAL NEWNYM sent via stem")
255
+
256
+ # ------------------------------------------------------------------
257
+ # IP query
258
+ # ------------------------------------------------------------------
259
+
260
+ async def get_current_exit_ip(self) -> Optional[str]:
261
+ """
262
+ Return the current Tor exit IP, or None on failure.
263
+
264
+ Attempts to fetch a JSON IP-check endpoint through the Tor
265
+ SOCKS proxy using httpx.
266
+ """
267
+ try:
268
+ import httpx # type: ignore[import-untyped]
269
+ except ImportError:
270
+ log.error("httpx not installed: pip install httpx[socks]")
271
+ return None
272
+
273
+ proxy_url = self.get_socks_url()
274
+ try:
275
+ async with httpx.AsyncClient(proxy=proxy_url, timeout=20) as client:
276
+ resp = await client.get(_IP_CHECK_URL)
277
+ resp.raise_for_status()
278
+ data = resp.json()
279
+ ip: str = data.get("IP") or data.get("ip") or str(data)
280
+ log.info("Exit IP: %s", ip)
281
+ return ip
282
+ except Exception as exc: # noqa: BLE001
283
+ log.warning("Could not determine Tor exit IP: %s", exc)
284
+ return None
285
+
286
+ # ------------------------------------------------------------------
287
+ # Private helpers
288
+ # ------------------------------------------------------------------
289
+
290
+ async def _wait_for_bootstrap(self) -> bool:
291
+ """
292
+ Read Tor's stdout until it reports 100% bootstrap or timeout.
293
+ Returns True when bootstrap completes.
294
+ """
295
+ if self._process is None or self._process.stdout is None:
296
+ return False
297
+
298
+ start = time.monotonic()
299
+ deadline = start + _BOOTSTRAP_TIMEOUT
300
+ best = -1
301
+ while time.monotonic() < min(deadline, start + _BOOTSTRAP_MAX):
302
+ try:
303
+ line_bytes = await asyncio.wait_for(
304
+ self._process.stdout.readline(), timeout=_BOOTSTRAP_POLL
305
+ )
306
+ except asyncio.TimeoutError:
307
+ # Tor may still be starting; check if process died
308
+ if self._process.returncode is not None:
309
+ log.error("Tor process exited unexpectedly (rc=%d)", self._process.returncode)
310
+ return False
311
+ continue
312
+
313
+ if not line_bytes:
314
+ # EOF -- process ended
315
+ return False
316
+
317
+ line = line_bytes.decode(errors="replace").strip()
318
+ log.debug("[Tor stdout] %s", line)
319
+
320
+ m = _BOOTSTRAP_RE.search(line)
321
+ if m:
322
+ pct = int(m.group(1))
323
+ if pct >= 100:
324
+ return True
325
+ if pct > best:
326
+ best = pct
327
+ deadline = time.monotonic() + _BOOTSTRAP_TIMEOUT
328
+
329
+ return False
330
+
331
+
332
+ # ---------------------------------------------------------------------------
333
+ # torrc builder
334
+ # ---------------------------------------------------------------------------
335
+
336
+ def _torrc_path_value(path: Path) -> str:
337
+ r"""
338
+ Quote a path for torrc. Paths with spaces (e.g. ``C:\Users\Jane Doe``)
339
+ must be quoted, and inside quotes torrc treats backslash as an escape,
340
+ so backslashes are doubled.
341
+ """
342
+ escaped = str(path).replace("\\", "\\\\").replace('"', '\\"')
343
+ return f'"{escaped}"'
344
+
345
+
346
+ def _geoip_dir(binary: Path) -> Optional[Path]:
347
+ """The expert bundle ships ``data/geoip*`` next to ``tor/``."""
348
+ data = binary.parent.parent / "data"
349
+ return data if (data / "geoip").is_file() else None
350
+
351
+
352
+ def _build_torrc(
353
+ data_dir: Path,
354
+ socks_port: int,
355
+ control_port: int,
356
+ geoip_dir: Optional[Path] = None,
357
+ ) -> str:
358
+ """Generate a minimal torrc for the managed Tor process."""
359
+ lines = [
360
+ f"DataDirectory {_torrc_path_value(data_dir)}",
361
+ f"SocksPort 127.0.0.1:{socks_port}",
362
+ f"ControlPort 127.0.0.1:{control_port}",
363
+ "CookieAuthentication 1",
364
+ "Log notice stdout",
365
+ # Tor exits by itself when this process dies (crash, TerminateProcess).
366
+ f"__OwningControllerProcess {os.getpid()}",
367
+ ]
368
+ if geoip_dir is not None:
369
+ lines.append(f"GeoIPFile {_torrc_path_value(geoip_dir / 'geoip')}")
370
+ if (geoip_dir / "geoip6").is_file():
371
+ lines.append(f"GeoIPv6File {_torrc_path_value(geoip_dir / 'geoip6')}")
372
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,208 @@
1
+ """
2
+ warp_keeper.py - Cloudflare WARP manager for opencode-unlimited.
3
+
4
+ Manages warp-cli lifecycle: connect, disconnect, rotate, status.
5
+ Supports Windows and Linux warp-cli binary paths.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import shutil
12
+ import sys
13
+ from typing import Any
14
+
15
+ from rich.console import Console
16
+ import logging
17
+
18
+ log = logging.getLogger(__name__)
19
+ console = Console()
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Platform-specific binary name
23
+ # ---------------------------------------------------------------------------
24
+ _WARP_BINARY_WINDOWS = "warp-cli.exe"
25
+ _WARP_BINARY_UNIX = "warp-cli"
26
+
27
+
28
+ def _warp_binary() -> str:
29
+ """Return the platform-appropriate warp-cli binary name."""
30
+ return _WARP_BINARY_WINDOWS if sys.platform == "win32" else _WARP_BINARY_UNIX
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # WarpKeeper
35
+ # ---------------------------------------------------------------------------
36
+
37
+ class WarpKeeper:
38
+ """Manages a Cloudflare WARP connection and exposes a local SOCKS5 proxy."""
39
+
40
+ # Polling configuration
41
+ _CONNECT_POLL_INTERVAL: float = 1.5
42
+ _CONNECT_TIMEOUT: float = 30.0
43
+
44
+ def __init__(self, socks_port: int = 40000) -> None:
45
+ self.socks_port = socks_port
46
+ self._binary = _warp_binary()
47
+ log.debug("WarpKeeper initialised (socks_port=%d, binary=%s)", socks_port, self._binary)
48
+
49
+ # ------------------------------------------------------------------
50
+ # Public helpers
51
+ # ------------------------------------------------------------------
52
+
53
+ def is_available(self) -> bool:
54
+ """Return True if warp-cli is found on PATH."""
55
+ found = shutil.which(self._binary) is not None
56
+ log.debug("warp-cli availability: %s", found)
57
+ return found
58
+
59
+ def get_socks_url(self) -> str:
60
+ """Return the SOCKS5 URL that WARP exposes locally."""
61
+ return f"socks5://127.0.0.1:{self.socks_port}"
62
+
63
+ # ------------------------------------------------------------------
64
+ # Async operations
65
+ # ------------------------------------------------------------------
66
+
67
+ async def connect(self) -> bool:
68
+ """
69
+ Issue `warp-cli connect` and poll until the daemon reports
70
+ a connected state. Returns True on success, False on timeout.
71
+ """
72
+ if not self.is_available():
73
+ log.warning("warp-cli not found -- cannot connect")
74
+ return False
75
+
76
+ log.info("[bold cyan]WARP[/] Connecting...", extra={"markup": True})
77
+ await self._run(self._binary, "connect")
78
+
79
+ deadline = asyncio.get_event_loop().time() + self._CONNECT_TIMEOUT
80
+ while asyncio.get_event_loop().time() < deadline:
81
+ status = await self.get_status()
82
+ if status.get("connected"):
83
+ log.info(
84
+ "[bold green]WARP[/] Connected -- IP: %s",
85
+ status.get("ip", "unknown"),
86
+ extra={"markup": True},
87
+ )
88
+ return True
89
+ await asyncio.sleep(self._CONNECT_POLL_INTERVAL)
90
+
91
+ log.error("[bold red]WARP[/] Connection timed out after %.0fs", self._CONNECT_TIMEOUT, extra={"markup": True})
92
+ return False
93
+
94
+ async def disconnect(self) -> None:
95
+ """Issue `warp-cli disconnect`."""
96
+ if not self.is_available():
97
+ log.warning("warp-cli not found -- cannot disconnect")
98
+ return
99
+ log.info("[bold cyan]WARP[/] Disconnecting...", extra={"markup": True})
100
+ await self._run(self._binary, "disconnect")
101
+ log.info("[bold yellow]WARP[/] Disconnected", extra={"markup": True})
102
+
103
+ async def rotate(self) -> bool:
104
+ """
105
+ Disconnect then reconnect to obtain a new egress IP.
106
+ Returns True if the reconnect succeeded.
107
+ """
108
+ log.info("[bold cyan]WARP[/] Rotating IP...", extra={"markup": True})
109
+ await self.disconnect()
110
+ # Short pause to let WARP release the tunnel
111
+ await asyncio.sleep(2.0)
112
+ return await self.connect()
113
+
114
+ async def get_status(self) -> dict[str, Any]:
115
+ """
116
+ Return a dict with keys:
117
+ connected (bool), ip (str | None), endpoint (str | None)
118
+ Parses `warp-cli status` output.
119
+ """
120
+ if not self.is_available():
121
+ return {"connected": False, "ip": None, "endpoint": None}
122
+
123
+ stdout, _, returncode = await self._run(self._binary, "status", capture=True)
124
+ if returncode != 0:
125
+ return {"connected": False, "ip": None, "endpoint": None}
126
+
127
+ return _parse_warp_status(stdout)
128
+
129
+ # ------------------------------------------------------------------
130
+ # Internal helpers
131
+ # ------------------------------------------------------------------
132
+
133
+ async def _run(
134
+ self,
135
+ *args: str,
136
+ capture: bool = False,
137
+ ) -> tuple[str, str, int]:
138
+ """
139
+ Run a subprocess using asyncio.create_subprocess_exec.
140
+
141
+ Returns (stdout, stderr, returncode).
142
+ When capture=False stdout/stderr are inherited and the tuple
143
+ contains empty strings.
144
+ """
145
+ if capture:
146
+ proc = await asyncio.create_subprocess_exec(
147
+ *args,
148
+ stdout=asyncio.subprocess.PIPE,
149
+ stderr=asyncio.subprocess.PIPE,
150
+ )
151
+ raw_out, raw_err = await proc.communicate()
152
+ stdout = raw_out.decode(errors="replace")
153
+ stderr = raw_err.decode(errors="replace")
154
+ log.debug("CMD %s -> rc=%d\nstdout: %s", args, proc.returncode, stdout.strip())
155
+ return stdout, stderr, proc.returncode or 0
156
+ else:
157
+ proc = await asyncio.create_subprocess_exec(
158
+ *args,
159
+ stdout=asyncio.subprocess.DEVNULL,
160
+ stderr=asyncio.subprocess.DEVNULL,
161
+ )
162
+ await proc.communicate()
163
+ return "", "", proc.returncode or 0
164
+
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # Status parser
168
+ # ---------------------------------------------------------------------------
169
+
170
+ def _parse_warp_status(output: str) -> dict[str, Any]:
171
+ """
172
+ Parse the text output of `warp-cli status`.
173
+
174
+ Example output (Linux):
175
+ Status update: Connected
176
+ Success
177
+ IP: 104.28.x.x
178
+ ...
179
+
180
+ Example output (Windows / newer CLI):
181
+ Status : Connected
182
+ Tunnel IP : 172.16.0.2
183
+ Endpoint : 162.159.x.x:2408
184
+ """
185
+ result: dict[str, Any] = {"connected": False, "ip": None, "endpoint": None}
186
+
187
+ lower = output.lower()
188
+ # Connection state
189
+ if "connected" in lower and "disconnected" not in lower:
190
+ result["connected"] = True
191
+
192
+ for line in output.splitlines():
193
+ line_stripped = line.strip()
194
+ line_lower = line_stripped.lower()
195
+
196
+ # IP address
197
+ if line_lower.startswith("ip:") or "tunnel ip" in line_lower:
198
+ parts = line_stripped.split(":", 1)
199
+ if len(parts) == 2:
200
+ result["ip"] = parts[1].strip()
201
+
202
+ # Endpoint
203
+ elif "endpoint" in line_lower:
204
+ parts = line_stripped.split(":", 1)
205
+ if len(parts) == 2:
206
+ result["endpoint"] = parts[1].strip()
207
+
208
+ return result
File without changes