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.
- opencode_unlimited/__init__.py +12 -0
- opencode_unlimited/__main__.py +6 -0
- opencode_unlimited/cli.py +921 -0
- opencode_unlimited/config.py +213 -0
- opencode_unlimited/constants.py +113 -0
- opencode_unlimited/daemon.py +223 -0
- opencode_unlimited/dashboard/__init__.py +1 -0
- opencode_unlimited/dashboard/server.py +503 -0
- opencode_unlimited/egress/__init__.py +0 -0
- opencode_unlimited/egress/clean_endpoint.py +182 -0
- opencode_unlimited/egress/tor_installer.py +379 -0
- opencode_unlimited/egress/tor_manager.py +372 -0
- opencode_unlimited/egress/warp_keeper.py +208 -0
- opencode_unlimited/guards/__init__.py +0 -0
- opencode_unlimited/guards/auto_resume.py +267 -0
- opencode_unlimited/guards/zen_guard.py +269 -0
- opencode_unlimited/launcher.py +379 -0
- opencode_unlimited/pool/__init__.py +1 -0
- opencode_unlimited/pool/account_pool.py +235 -0
- opencode_unlimited/proxy/__init__.py +1 -0
- opencode_unlimited/proxy/proxy_chain.py +344 -0
- opencode_unlimited/proxy/zen_proxy.py +701 -0
- opencode_unlimited-0.1.0.dist-info/METADATA +283 -0
- opencode_unlimited-0.1.0.dist-info/RECORD +27 -0
- opencode_unlimited-0.1.0.dist-info/WHEEL +4 -0
- opencode_unlimited-0.1.0.dist-info/entry_points.txt +2 -0
- opencode_unlimited-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""
|
|
2
|
+
config.py - Stdlib dataclass configuration model and TOML persistence for ocu.
|
|
3
|
+
|
|
4
|
+
Uses pure Python stdlib dataclasses (no pydantic/Rust extensions) so it
|
|
5
|
+
installs and runs cleanly on Termux (Android), Linux, macOS, and Windows.
|
|
6
|
+
|
|
7
|
+
Usage::
|
|
8
|
+
|
|
9
|
+
from opencode_unlimited.config import load_config, save_config, reset_config
|
|
10
|
+
|
|
11
|
+
cfg = load_config()
|
|
12
|
+
cfg.proxy_port = 9000
|
|
13
|
+
save_config(cfg)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import logging
|
|
19
|
+
import sys
|
|
20
|
+
from dataclasses import asdict, dataclass, field
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from opencode_unlimited.constants import (
|
|
24
|
+
CONFIG_DIR,
|
|
25
|
+
CONFIG_FILE,
|
|
26
|
+
DEFAULT_DASHBOARD_PORT,
|
|
27
|
+
DEFAULT_PROXY_PORT,
|
|
28
|
+
OPENCODE_API_HOST,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
# tomllib / tomli import (stdlib in 3.11+, package on 3.10)
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
if sys.version_info >= (3, 11):
|
|
36
|
+
import tomllib
|
|
37
|
+
else:
|
|
38
|
+
try:
|
|
39
|
+
import tomllib # type: ignore[no-redef]
|
|
40
|
+
except ModuleNotFoundError:
|
|
41
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
import tomli_w as _tomli_w
|
|
45
|
+
|
|
46
|
+
def _dumps(data: dict[str, Any]) -> str:
|
|
47
|
+
return _tomli_w.dumps(data)
|
|
48
|
+
|
|
49
|
+
except ModuleNotFoundError: # pragma: no cover
|
|
50
|
+
def _dumps(data: dict[str, Any]) -> str: # type: ignore[misc]
|
|
51
|
+
"""Minimal TOML serialiser (no nested tables, strings + primitives only)."""
|
|
52
|
+
lines: list[str] = []
|
|
53
|
+
for key, value in data.items():
|
|
54
|
+
if isinstance(value, bool):
|
|
55
|
+
lines.append(f"{key} = {'true' if value else 'false'}")
|
|
56
|
+
elif isinstance(value, (int, float)):
|
|
57
|
+
lines.append(f"{key} = {value}")
|
|
58
|
+
elif isinstance(value, str):
|
|
59
|
+
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
|
|
60
|
+
lines.append(f'{key} = "{escaped}"')
|
|
61
|
+
elif isinstance(value, list):
|
|
62
|
+
items = ", ".join(
|
|
63
|
+
f'"{v}"' if isinstance(v, str) else str(v) for v in value
|
|
64
|
+
)
|
|
65
|
+
lines.append(f"{key} = [{items}]")
|
|
66
|
+
else:
|
|
67
|
+
lines.append(f'{key} = "{value}"')
|
|
68
|
+
return "\n".join(lines) + "\n"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
logger = logging.getLogger(__name__)
|
|
72
|
+
|
|
73
|
+
_VALID_LOG_LEVELS = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
|
74
|
+
# Must match proxy_chain.LANE_ALIASES ("clean" is an alias of "clean_endpoint").
|
|
75
|
+
_VALID_LANES = {"direct", "clean", "clean_endpoint", "warp", "tor"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _validate_port(name: str, value: Any) -> int:
|
|
79
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
80
|
+
try:
|
|
81
|
+
value = int(value)
|
|
82
|
+
except (TypeError, ValueError) as exc:
|
|
83
|
+
raise ValueError(f"{name} must be an integer, got {value!r}") from exc
|
|
84
|
+
if value < 1 or value > 65535:
|
|
85
|
+
raise ValueError(f"{name} must be between 1 and 65535, got {value}")
|
|
86
|
+
return value
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _validate_bool(name: str, value: Any) -> bool:
|
|
90
|
+
if isinstance(value, bool):
|
|
91
|
+
return value
|
|
92
|
+
if isinstance(value, str):
|
|
93
|
+
low = value.strip().lower()
|
|
94
|
+
if low in {"true", "1", "yes", "on"}:
|
|
95
|
+
return True
|
|
96
|
+
if low in {"false", "0", "no", "off"}:
|
|
97
|
+
return False
|
|
98
|
+
raise ValueError(f"{name} must be a boolean, got {value!r}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _validate_log_level(value: Any) -> str:
|
|
102
|
+
normalised = str(value).upper()
|
|
103
|
+
if normalised not in _VALID_LOG_LEVELS:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"log_level must be one of {sorted(_VALID_LOG_LEVELS)}, got {value!r}"
|
|
106
|
+
)
|
|
107
|
+
return normalised
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _validate_lanes(value: Any) -> list[str]:
|
|
111
|
+
if not isinstance(value, list):
|
|
112
|
+
raise TypeError("lanes_priority must be a list of strings")
|
|
113
|
+
invalid = [lane for lane in value if str(lane).lower() not in _VALID_LANES]
|
|
114
|
+
if invalid:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"Unknown lane(s) in lanes_priority: {invalid}. "
|
|
117
|
+
f"Valid values are: {sorted(_VALID_LANES)}"
|
|
118
|
+
)
|
|
119
|
+
return [str(lane).lower() for lane in value]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------------------
|
|
123
|
+
# Config model
|
|
124
|
+
# ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class OCUConfig:
|
|
129
|
+
"""Runtime configuration for opencode-unlimited.
|
|
130
|
+
|
|
131
|
+
All fields carry sensible defaults so the application starts correctly
|
|
132
|
+
even without an existing config file.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
proxy_port: int = DEFAULT_PROXY_PORT
|
|
136
|
+
dashboard_port: int = DEFAULT_DASHBOARD_PORT
|
|
137
|
+
enable_warp: bool = True
|
|
138
|
+
enable_tor: bool = True
|
|
139
|
+
enable_clean_endpoints: bool = True
|
|
140
|
+
auto_resume: bool = True
|
|
141
|
+
log_level: str = "INFO"
|
|
142
|
+
lanes_priority: list[str] = field(default_factory=lambda: ["clean", "warp", "tor"])
|
|
143
|
+
opencode_api_host: str = OPENCODE_API_HOST
|
|
144
|
+
opencode_cli_path: str = ""
|
|
145
|
+
opencode_desktop_path: str = ""
|
|
146
|
+
|
|
147
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
148
|
+
if name in {"proxy_port", "dashboard_port"}:
|
|
149
|
+
value = _validate_port(name, value)
|
|
150
|
+
elif name in {"enable_warp", "enable_tor", "enable_clean_endpoints", "auto_resume"}:
|
|
151
|
+
value = _validate_bool(name, value)
|
|
152
|
+
elif name == "log_level":
|
|
153
|
+
value = _validate_log_level(value)
|
|
154
|
+
elif name == "lanes_priority":
|
|
155
|
+
value = _validate_lanes(value)
|
|
156
|
+
elif name in {"opencode_api_host", "opencode_cli_path", "opencode_desktop_path"}:
|
|
157
|
+
value = str(value)
|
|
158
|
+
super().__setattr__(name, value)
|
|
159
|
+
|
|
160
|
+
def model_dump(self) -> dict[str, Any]:
|
|
161
|
+
"""Return a plain dict of all config fields."""
|
|
162
|
+
return asdict(self)
|
|
163
|
+
|
|
164
|
+
def as_toml_dict(self) -> dict[str, Any]:
|
|
165
|
+
"""Return a plain dict suitable for TOML serialisation."""
|
|
166
|
+
return self.model_dump()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---------------------------------------------------------------------------
|
|
170
|
+
# Persistence helpers
|
|
171
|
+
# ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def load_config() -> OCUConfig:
|
|
175
|
+
"""Load configuration from ``CONFIG_FILE``.
|
|
176
|
+
|
|
177
|
+
If the file does not exist or is unreadable, returns a default
|
|
178
|
+
``OCUConfig`` instance. Partial configs are supported: missing keys
|
|
179
|
+
fall back to their field defaults.
|
|
180
|
+
"""
|
|
181
|
+
if not CONFIG_FILE.exists():
|
|
182
|
+
logger.debug("Config file not found at %s, using defaults.", CONFIG_FILE)
|
|
183
|
+
return OCUConfig()
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
raw = CONFIG_FILE.read_bytes()
|
|
187
|
+
data: dict[str, Any] = tomllib.loads(raw.decode("utf-8"))
|
|
188
|
+
valid_keys = set(OCUConfig.__dataclass_fields__.keys())
|
|
189
|
+
filtered = {k: v for k, v in data.items() if k in valid_keys}
|
|
190
|
+
return OCUConfig(**filtered)
|
|
191
|
+
except Exception as exc: # noqa: BLE001
|
|
192
|
+
logger.warning(
|
|
193
|
+
"Failed to parse config file %s (%s). Falling back to defaults.",
|
|
194
|
+
CONFIG_FILE,
|
|
195
|
+
exc,
|
|
196
|
+
)
|
|
197
|
+
return OCUConfig()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def save_config(cfg: OCUConfig) -> None:
|
|
201
|
+
"""Persist *cfg* to ``CONFIG_FILE`` as TOML."""
|
|
202
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
203
|
+
toml_str = _dumps(cfg.as_toml_dict())
|
|
204
|
+
CONFIG_FILE.write_text(toml_str, encoding="utf-8")
|
|
205
|
+
logger.debug("Config saved to %s.", CONFIG_FILE)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def reset_config() -> OCUConfig:
|
|
209
|
+
"""Reset configuration to factory defaults."""
|
|
210
|
+
default_cfg = OCUConfig()
|
|
211
|
+
save_config(default_cfg)
|
|
212
|
+
logger.info("Configuration reset to defaults at %s.", CONFIG_FILE)
|
|
213
|
+
return default_cfg
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""
|
|
2
|
+
constants.py - All package-wide constants for opencode-unlimited.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# ---------------------------------------------------------------------------
|
|
12
|
+
# Network / proxy ports
|
|
13
|
+
# ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
DEFAULT_PROXY_PORT: int = 8877
|
|
16
|
+
"""Local HTTP/HTTPS proxy port that ocu listens on."""
|
|
17
|
+
|
|
18
|
+
TOR_SOCKS_PORT: int = 9050
|
|
19
|
+
"""SOCKS5 port exposed by the local Tor daemon."""
|
|
20
|
+
|
|
21
|
+
TOR_CONTROL_PORT: int = 9051
|
|
22
|
+
"""Control port used to send NEWNYM signals to Tor."""
|
|
23
|
+
|
|
24
|
+
WARP_SOCKS_PORT: int = 40000
|
|
25
|
+
"""SOCKS5 port exposed by the Cloudflare WARP daemon (warp-svc)."""
|
|
26
|
+
|
|
27
|
+
DEFAULT_DASHBOARD_PORT: int = 7979
|
|
28
|
+
"""Port for the ocu HTTP status / metrics endpoint."""
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
# HTTP status codes
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
RATE_LIMIT_STATUS_CODE: int = 429
|
|
35
|
+
"""HTTP status code that triggers an automatic lane rotation."""
|
|
36
|
+
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
# Platform-aware config directory
|
|
39
|
+
# ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
def _resolve_config_dir() -> Path:
|
|
42
|
+
"""Return the platform-appropriate config directory for opencode-unlimited."""
|
|
43
|
+
if sys.platform == "win32":
|
|
44
|
+
base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
|
|
45
|
+
elif sys.platform == "darwin":
|
|
46
|
+
base = Path.home() / "Library" / "Application Support"
|
|
47
|
+
else:
|
|
48
|
+
# XDG Base Directory Specification
|
|
49
|
+
xdg = os.environ.get("XDG_CONFIG_HOME", "")
|
|
50
|
+
base = Path(xdg) if xdg else Path.home() / ".config"
|
|
51
|
+
return base / "opencode-unlimited"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
CONFIG_DIR: Path = _resolve_config_dir()
|
|
55
|
+
"""Directory that stores all opencode-unlimited runtime files."""
|
|
56
|
+
|
|
57
|
+
CONFIG_FILE: Path = CONFIG_DIR / "config.toml"
|
|
58
|
+
"""Path to the TOML configuration file."""
|
|
59
|
+
|
|
60
|
+
PID_FILE: Path = CONFIG_DIR / "ocu.pid"
|
|
61
|
+
"""Path to the proxy daemon PID file."""
|
|
62
|
+
|
|
63
|
+
LOG_FILE: Path = CONFIG_DIR / "ocu.log"
|
|
64
|
+
"""Path to the rotating proxy log file."""
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
# API host
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
OPENCODE_API_HOST: str = "api.opencode.ai"
|
|
71
|
+
"""Upstream OpenCode API hostname (without scheme)."""
|
|
72
|
+
|
|
73
|
+
# ---------------------------------------------------------------------------
|
|
74
|
+
# Clean anycast / public DNS endpoints
|
|
75
|
+
# Used as the first lane when neither Tor nor WARP is preferred.
|
|
76
|
+
# These are well-known public anycast IPs that are globally reachable.
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
CLEAN_ENDPOINTS: list[str] = [
|
|
80
|
+
"1.1.1.1", # Cloudflare DNS anycast
|
|
81
|
+
"1.0.0.1", # Cloudflare DNS anycast (secondary)
|
|
82
|
+
"8.8.8.8", # Google Public DNS anycast
|
|
83
|
+
"8.8.4.4", # Google Public DNS anycast (secondary)
|
|
84
|
+
"9.9.9.9", # Quad9 anycast
|
|
85
|
+
"149.112.112.112", # Quad9 secondary anycast
|
|
86
|
+
"208.67.222.222", # OpenDNS anycast
|
|
87
|
+
"208.67.220.220", # OpenDNS secondary anycast
|
|
88
|
+
"94.140.14.14", # AdGuard DNS anycast
|
|
89
|
+
"94.140.15.15", # AdGuard DNS secondary anycast
|
|
90
|
+
"185.228.168.9", # CleanBrowsing anycast
|
|
91
|
+
"76.76.2.0", # Control D anycast
|
|
92
|
+
]
|
|
93
|
+
"""
|
|
94
|
+
A list of publicly routable anycast IP addresses used as egress IPs
|
|
95
|
+
for the clean-endpoint lane. The proxy randomly selects from this list
|
|
96
|
+
to distribute outbound connections across multiple network paths.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# Misc
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
LOG_MAX_BYTES: int = 10 * 1024 * 1024 # 10 MB per log file
|
|
104
|
+
LOG_BACKUP_COUNT: int = 5 # keep 5 rotated log files
|
|
105
|
+
|
|
106
|
+
REQUEST_TIMEOUT_SECONDS: float = 30.0
|
|
107
|
+
"""Default timeout for upstream HTTP requests."""
|
|
108
|
+
|
|
109
|
+
LANE_COOLDOWN_SECONDS: float = 5.0
|
|
110
|
+
"""Minimum seconds to wait before re-trying a lane that returned 429."""
|
|
111
|
+
|
|
112
|
+
MAX_RETRIES_PER_LANE: int = 3
|
|
113
|
+
"""Maximum consecutive failures before marking a lane as degraded."""
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
daemon.py - Background service stack runner & cross-platform daemon spawner.
|
|
3
|
+
|
|
4
|
+
Runs ZenProxy, ZenGuard, AutoResume, TorManager, WarpKeeper, and optional
|
|
5
|
+
dashboard together in a single async event loop, and provides helpers to
|
|
6
|
+
spawn the stack as a detached background process on Windows, macOS, and Linux.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import functools
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import socket
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from typing import Optional
|
|
21
|
+
|
|
22
|
+
from opencode_unlimited.config import OCUConfig
|
|
23
|
+
from opencode_unlimited.constants import CONFIG_DIR, LOG_FILE, PID_FILE
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_port_open(host: str, port: int, timeout: float = 0.5) -> bool:
|
|
29
|
+
"""Return True if a TCP connection to (host, port) succeeds."""
|
|
30
|
+
try:
|
|
31
|
+
with socket.create_connection((host, port), timeout=timeout):
|
|
32
|
+
return True
|
|
33
|
+
except OSError:
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def wait_for_port(host: str, port: int, timeout: float = 10.0) -> bool:
|
|
38
|
+
"""Poll until (host, port) accepts TCP connections or timeout expires."""
|
|
39
|
+
deadline = time.monotonic() + timeout
|
|
40
|
+
while time.monotonic() < deadline:
|
|
41
|
+
if is_port_open(host, port, timeout=0.3):
|
|
42
|
+
return True
|
|
43
|
+
time.sleep(0.2)
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def run_stack(
|
|
48
|
+
cfg: OCUConfig,
|
|
49
|
+
*,
|
|
50
|
+
dashboard: bool = False,
|
|
51
|
+
stop_event: Optional[asyncio.Event] = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
"""
|
|
54
|
+
Start and run the full opencode-unlimited service stack:
|
|
55
|
+
- WarpKeeper (if enable_warp and warp-cli is available)
|
|
56
|
+
- TorManager (if enable_tor and tor is available)
|
|
57
|
+
- ProxyChain
|
|
58
|
+
- AutoResume + background state watcher
|
|
59
|
+
- ZenGuard (429 monitor + rotation trigger)
|
|
60
|
+
- ZenProxy (local HTTP/HTTPS proxy)
|
|
61
|
+
- Optional FastAPI dashboard
|
|
62
|
+
"""
|
|
63
|
+
from opencode_unlimited.egress.tor_manager import TorManager
|
|
64
|
+
from opencode_unlimited.egress.warp_keeper import WarpKeeper
|
|
65
|
+
from opencode_unlimited.guards.auto_resume import AutoResume
|
|
66
|
+
from opencode_unlimited.guards.zen_guard import ZenGuard
|
|
67
|
+
from opencode_unlimited.pool.account_pool import AccountPool
|
|
68
|
+
from opencode_unlimited.proxy.proxy_chain import Lane, ProxyChain
|
|
69
|
+
from opencode_unlimited.proxy.zen_proxy import ZenProxy
|
|
70
|
+
|
|
71
|
+
proxy_chain = ProxyChain(cfg)
|
|
72
|
+
account_pool = AccountPool()
|
|
73
|
+
auto_resume = AutoResume(cfg)
|
|
74
|
+
zen_guard = ZenGuard(proxy_chain, auto_resume_handler=auto_resume.resume)
|
|
75
|
+
|
|
76
|
+
tor_manager: Optional[TorManager] = None
|
|
77
|
+
warp_keeper: Optional[WarpKeeper] = None
|
|
78
|
+
|
|
79
|
+
if cfg.enable_warp:
|
|
80
|
+
wk = WarpKeeper()
|
|
81
|
+
if wk.is_available():
|
|
82
|
+
try:
|
|
83
|
+
if await wk.connect():
|
|
84
|
+
warp_keeper = wk
|
|
85
|
+
else:
|
|
86
|
+
logger.warning("WARP did not connect")
|
|
87
|
+
except Exception as exc:
|
|
88
|
+
logger.warning("WARP failed to start: %s", exc)
|
|
89
|
+
else:
|
|
90
|
+
logger.info("warp-cli not installed; skipping WARP startup")
|
|
91
|
+
|
|
92
|
+
if cfg.enable_tor:
|
|
93
|
+
tm = TorManager()
|
|
94
|
+
# start() also reuses a Tor that is already listening on the SOCKS
|
|
95
|
+
# port, so it is attempted even when no tor binary is installed.
|
|
96
|
+
try:
|
|
97
|
+
if await tm.start():
|
|
98
|
+
tor_manager = tm
|
|
99
|
+
else:
|
|
100
|
+
logger.warning("Tor is not available; run `ocu tor install`")
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
logger.warning("Tor failed to start: %s", exc)
|
|
103
|
+
|
|
104
|
+
# A lane whose SOCKS server isn't running would fail every request and
|
|
105
|
+
# add a connect timeout to each one, so take it out of rotation.
|
|
106
|
+
if warp_keeper is None:
|
|
107
|
+
proxy_chain.disable_lane(Lane.WARP)
|
|
108
|
+
if tor_manager is None:
|
|
109
|
+
proxy_chain.disable_lane(Lane.TOR)
|
|
110
|
+
|
|
111
|
+
if dashboard:
|
|
112
|
+
from opencode_unlimited.dashboard.server import create_app, run_dashboard
|
|
113
|
+
|
|
114
|
+
dash_app = create_app(proxy_chain, zen_guard, account_pool, cfg)
|
|
115
|
+
t = threading.Thread(
|
|
116
|
+
target=run_dashboard,
|
|
117
|
+
args=(dash_app, cfg.dashboard_port),
|
|
118
|
+
daemon=True,
|
|
119
|
+
)
|
|
120
|
+
t.start()
|
|
121
|
+
logger.info("Dashboard started on http://127.0.0.1:%d", cfg.dashboard_port)
|
|
122
|
+
|
|
123
|
+
proxy = ZenProxy(
|
|
124
|
+
host="127.0.0.1",
|
|
125
|
+
port=cfg.proxy_port,
|
|
126
|
+
proxy_chain=proxy_chain,
|
|
127
|
+
zen_guard_callback=functools.partial(zen_guard.on_rate_limit, rotate=False),
|
|
128
|
+
)
|
|
129
|
+
await proxy.start()
|
|
130
|
+
|
|
131
|
+
watcher_task = asyncio.create_task(auto_resume.watch_opencode_state())
|
|
132
|
+
|
|
133
|
+
evt = stop_event or asyncio.Event()
|
|
134
|
+
try:
|
|
135
|
+
await evt.wait()
|
|
136
|
+
except asyncio.CancelledError:
|
|
137
|
+
pass
|
|
138
|
+
finally:
|
|
139
|
+
watcher_task.cancel()
|
|
140
|
+
try:
|
|
141
|
+
await watcher_task
|
|
142
|
+
except asyncio.CancelledError:
|
|
143
|
+
pass
|
|
144
|
+
await proxy.stop()
|
|
145
|
+
if tor_manager is not None:
|
|
146
|
+
await tor_manager.stop()
|
|
147
|
+
if warp_keeper is not None:
|
|
148
|
+
logger.debug("Leaving WARP connection state as-is on shutdown")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def spawn_background_daemon(
|
|
152
|
+
proxy_port: int,
|
|
153
|
+
*,
|
|
154
|
+
no_warp: bool = False,
|
|
155
|
+
no_tor: bool = False,
|
|
156
|
+
dashboard: bool = False,
|
|
157
|
+
verbose: bool = False,
|
|
158
|
+
startup_timeout: float = 330.0,
|
|
159
|
+
) -> int:
|
|
160
|
+
"""
|
|
161
|
+
Spawn `ocu` proxy stack as a detached background process (cross-platform).
|
|
162
|
+
Returns the child PID once the proxy port is listening.
|
|
163
|
+
"""
|
|
164
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
165
|
+
|
|
166
|
+
cmd = [
|
|
167
|
+
sys.executable,
|
|
168
|
+
"-m",
|
|
169
|
+
"opencode_unlimited",
|
|
170
|
+
"_serve",
|
|
171
|
+
"--proxy-port",
|
|
172
|
+
str(proxy_port),
|
|
173
|
+
]
|
|
174
|
+
if no_warp:
|
|
175
|
+
cmd.append("--no-warp")
|
|
176
|
+
if no_tor:
|
|
177
|
+
cmd.append("--no-tor")
|
|
178
|
+
if dashboard:
|
|
179
|
+
cmd.append("--dashboard")
|
|
180
|
+
if verbose:
|
|
181
|
+
cmd.append("--verbose")
|
|
182
|
+
|
|
183
|
+
log_fh = open(LOG_FILE, "a", encoding="utf-8")
|
|
184
|
+
|
|
185
|
+
popen_kwargs: dict = {
|
|
186
|
+
"stdin": subprocess.DEVNULL,
|
|
187
|
+
"stdout": log_fh,
|
|
188
|
+
"stderr": log_fh,
|
|
189
|
+
"close_fds": True,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if sys.platform == "win32":
|
|
193
|
+
creationflags = (
|
|
194
|
+
getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
|
|
195
|
+
| getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
|
|
196
|
+
| getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
|
|
197
|
+
)
|
|
198
|
+
popen_kwargs["creationflags"] = creationflags
|
|
199
|
+
else:
|
|
200
|
+
popen_kwargs["start_new_session"] = True
|
|
201
|
+
|
|
202
|
+
proc = subprocess.Popen(cmd, **popen_kwargs)
|
|
203
|
+
log_fh.close()
|
|
204
|
+
|
|
205
|
+
# The proxy port opens only after Tor/WARP startup, and a cold Tor
|
|
206
|
+
# bootstrap can take minutes (TorManager caps it at 300s).
|
|
207
|
+
deadline = time.monotonic() + startup_timeout
|
|
208
|
+
while not is_port_open("127.0.0.1", proxy_port, timeout=0.3):
|
|
209
|
+
if proc.poll() is not None:
|
|
210
|
+
raise RuntimeError(
|
|
211
|
+
f"ocu daemon exited with code {proc.returncode} during startup; see {LOG_FILE}"
|
|
212
|
+
)
|
|
213
|
+
if time.monotonic() > deadline:
|
|
214
|
+
raise RuntimeError(
|
|
215
|
+
f"ocu daemon did not open port {proxy_port} within {startup_timeout:.0f}s; see {LOG_FILE}"
|
|
216
|
+
)
|
|
217
|
+
time.sleep(0.25)
|
|
218
|
+
# The daemon writes its own PID. On Windows venvs, proc.pid is the venv
|
|
219
|
+
# launcher, not the interpreter that actually runs the proxy.
|
|
220
|
+
try:
|
|
221
|
+
return int(PID_FILE.read_text(encoding="utf-8").strip())
|
|
222
|
+
except (OSError, ValueError):
|
|
223
|
+
return proc.pid
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# dashboard package
|