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,379 @@
|
|
|
1
|
+
"""
|
|
2
|
+
launcher.py - Cross-platform OpenCode detection, installation & launcher.
|
|
3
|
+
|
|
4
|
+
Locates OpenCode (CLI or Desktop) on Windows, macOS, and Linux.
|
|
5
|
+
If not found, offers an interactive prompt to install CLI, Desktop, or
|
|
6
|
+
specify a custom binary path, then launches OpenCode routed through ZenProxy.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import webbrowser
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Dict, List, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
from rich.console import Console
|
|
21
|
+
from rich.panel import Panel
|
|
22
|
+
from rich.table import Table
|
|
23
|
+
|
|
24
|
+
console = Console()
|
|
25
|
+
|
|
26
|
+
OPENCODE_DOWNLOAD_URL = "https://opencode.ai/download"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def find_opencode_cli(custom_path: str = "") -> Optional[str]:
|
|
30
|
+
"""Locate the `opencode` CLI binary on the current OS."""
|
|
31
|
+
if custom_path:
|
|
32
|
+
p = Path(custom_path).expanduser()
|
|
33
|
+
if p.is_file():
|
|
34
|
+
return str(p)
|
|
35
|
+
|
|
36
|
+
candidates = ["opencode"]
|
|
37
|
+
if sys.platform == "win32":
|
|
38
|
+
candidates = ["opencode.exe", "opencode.cmd", "opencode"]
|
|
39
|
+
|
|
40
|
+
for name in candidates:
|
|
41
|
+
found = shutil.which(name)
|
|
42
|
+
if found:
|
|
43
|
+
return found
|
|
44
|
+
|
|
45
|
+
home = Path.home()
|
|
46
|
+
extra_paths: List[Path] = []
|
|
47
|
+
if sys.platform == "win32":
|
|
48
|
+
appdata = Path(os.environ.get("APPDATA", home / "AppData" / "Roaming"))
|
|
49
|
+
localappdata = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
|
|
50
|
+
extra_paths += [
|
|
51
|
+
appdata / "npm" / "opencode.cmd",
|
|
52
|
+
home / ".opencode" / "bin" / "opencode.exe",
|
|
53
|
+
localappdata / "Programs" / "opencode" / "opencode.exe",
|
|
54
|
+
]
|
|
55
|
+
else:
|
|
56
|
+
extra_paths += [
|
|
57
|
+
home / ".opencode" / "bin" / "opencode",
|
|
58
|
+
home / ".local" / "bin" / "opencode",
|
|
59
|
+
Path("/usr/local/bin/opencode"),
|
|
60
|
+
Path("/opt/homebrew/bin/opencode"),
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
for path in extra_paths:
|
|
64
|
+
if path.is_file():
|
|
65
|
+
return str(path)
|
|
66
|
+
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def find_opencode_desktop(custom_path: str = "") -> Optional[Path]:
|
|
71
|
+
"""Locate the OpenCode Desktop application on Windows, macOS, or Linux."""
|
|
72
|
+
if custom_path:
|
|
73
|
+
p = Path(custom_path).expanduser()
|
|
74
|
+
if p.exists():
|
|
75
|
+
return p
|
|
76
|
+
|
|
77
|
+
home = Path.home()
|
|
78
|
+
|
|
79
|
+
if sys.platform == "win32":
|
|
80
|
+
localappdata = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
|
|
81
|
+
program_files = Path(os.environ.get("ProgramFiles", "C:\\Program Files"))
|
|
82
|
+
candidates = [
|
|
83
|
+
localappdata / "Programs" / "opencode" / "OpenCode.exe",
|
|
84
|
+
localappdata / "Programs" / "OpenCode" / "OpenCode.exe",
|
|
85
|
+
localappdata / "opencode" / "OpenCode.exe",
|
|
86
|
+
program_files / "OpenCode" / "OpenCode.exe",
|
|
87
|
+
]
|
|
88
|
+
for p in candidates:
|
|
89
|
+
if p.is_file():
|
|
90
|
+
return p
|
|
91
|
+
elif sys.platform == "darwin":
|
|
92
|
+
candidates = [
|
|
93
|
+
Path("/Applications/OpenCode.app"),
|
|
94
|
+
home / "Applications" / "OpenCode.app",
|
|
95
|
+
]
|
|
96
|
+
for p in candidates:
|
|
97
|
+
if p.exists():
|
|
98
|
+
return p
|
|
99
|
+
else:
|
|
100
|
+
for name in ("opencode-desktop", "OpenCode", "opencode-app"):
|
|
101
|
+
found = shutil.which(name)
|
|
102
|
+
if found:
|
|
103
|
+
return Path(found)
|
|
104
|
+
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def detect_opencode(cfg=None) -> Dict[str, Optional[str]]:
|
|
109
|
+
"""Return detected paths for OpenCode CLI and Desktop."""
|
|
110
|
+
cli_custom = getattr(cfg, "opencode_cli_path", "") if cfg else ""
|
|
111
|
+
desk_custom = getattr(cfg, "opencode_desktop_path", "") if cfg else ""
|
|
112
|
+
cli = find_opencode_cli(cli_custom)
|
|
113
|
+
desk = find_opencode_desktop(desk_custom)
|
|
114
|
+
return {
|
|
115
|
+
"cli": cli,
|
|
116
|
+
"desktop": str(desk) if desk else None,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def print_detection_table(detected: Dict[str, Optional[str]]) -> None:
|
|
121
|
+
"""Print a Rich table showing which OpenCode targets are installed."""
|
|
122
|
+
table = Table(title="OpenCode Detection", show_lines=True)
|
|
123
|
+
table.add_column("Target", style="cyan")
|
|
124
|
+
table.add_column("Status")
|
|
125
|
+
table.add_column("Path", style="dim")
|
|
126
|
+
|
|
127
|
+
cli_path = detected.get("cli")
|
|
128
|
+
desk_path = detected.get("desktop")
|
|
129
|
+
|
|
130
|
+
table.add_row(
|
|
131
|
+
"OpenCode CLI",
|
|
132
|
+
"[green]Found[/green]" if cli_path else "[yellow]Not Found[/yellow]",
|
|
133
|
+
cli_path or "--",
|
|
134
|
+
)
|
|
135
|
+
table.add_row(
|
|
136
|
+
"OpenCode Desktop",
|
|
137
|
+
"[green]Found[/green]" if desk_path else "[yellow]Not Found[/yellow]",
|
|
138
|
+
desk_path or "--",
|
|
139
|
+
)
|
|
140
|
+
console.print(table)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def install_opencode_cli() -> bool:
|
|
144
|
+
"""Attempt to install OpenCode CLI using the best available method on this OS."""
|
|
145
|
+
npm = shutil.which("npm")
|
|
146
|
+
brew = shutil.which("brew")
|
|
147
|
+
curl = shutil.which("curl")
|
|
148
|
+
|
|
149
|
+
methods: List[Tuple[str, List[str]]] = []
|
|
150
|
+
if sys.platform != "win32" and brew:
|
|
151
|
+
methods.append(("Homebrew (brew install anomalyco/tap/opencode)", ["brew", "install", "anomalyco/tap/opencode"]))
|
|
152
|
+
if npm:
|
|
153
|
+
methods.append(("npm (npm install -g opencode-ai)", [npm, "install", "-g", "opencode-ai"]))
|
|
154
|
+
if sys.platform != "win32" and curl:
|
|
155
|
+
methods.append(("Official install script (curl -fsSL https://opencode.ai/install | bash)", ["bash", "-c", "curl -fsSL https://opencode.ai/install | bash"]))
|
|
156
|
+
if sys.platform == "win32":
|
|
157
|
+
scoop = shutil.which("scoop")
|
|
158
|
+
choco = shutil.which("choco")
|
|
159
|
+
if scoop:
|
|
160
|
+
methods.append(("Scoop (scoop install opencode)", [scoop, "install", "opencode"]))
|
|
161
|
+
if choco:
|
|
162
|
+
methods.append(("Chocolatey (choco install opencode -y)", [choco, "install", "opencode", "-y"]))
|
|
163
|
+
|
|
164
|
+
if not methods:
|
|
165
|
+
console.print(
|
|
166
|
+
"[red]No supported package manager found (npm, brew, curl, scoop, choco).[/red]\n"
|
|
167
|
+
f"Please install OpenCode manually from [link={OPENCODE_DOWNLOAD_URL}]{OPENCODE_DOWNLOAD_URL}[/link]."
|
|
168
|
+
)
|
|
169
|
+
return False
|
|
170
|
+
|
|
171
|
+
console.print("\n[bold cyan]Available OpenCode CLI install methods:[/bold cyan]")
|
|
172
|
+
for idx, (label, _) in enumerate(methods, start=1):
|
|
173
|
+
console.print(f" [bold]{idx}.[/bold] {label}")
|
|
174
|
+
|
|
175
|
+
choice = typer.prompt("Select install method", default="1")
|
|
176
|
+
try:
|
|
177
|
+
idx = int(choice) - 1
|
|
178
|
+
if idx < 0 or idx >= len(methods):
|
|
179
|
+
raise ValueError
|
|
180
|
+
except ValueError:
|
|
181
|
+
console.print("[red]Invalid selection.[/red]")
|
|
182
|
+
return False
|
|
183
|
+
|
|
184
|
+
label, cmd = methods[idx]
|
|
185
|
+
console.print(f"[cyan]Running:[/cyan] {label}")
|
|
186
|
+
result = subprocess.run(cmd)
|
|
187
|
+
if result.returncode != 0:
|
|
188
|
+
console.print(f"[red]Installer exited with code {result.returncode}.[/red]")
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
return find_opencode_cli() is not None
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def install_opencode_desktop() -> bool:
|
|
195
|
+
"""Install or guide installation of OpenCode Desktop for the current OS."""
|
|
196
|
+
brew = shutil.which("brew")
|
|
197
|
+
winget = shutil.which("winget")
|
|
198
|
+
|
|
199
|
+
if sys.platform == "darwin" and brew:
|
|
200
|
+
if typer.confirm("Install OpenCode Desktop via Homebrew (`brew install --cask opencode`)?", default=True):
|
|
201
|
+
res = subprocess.run([brew, "install", "--cask", "opencode"])
|
|
202
|
+
if res.returncode == 0 and find_opencode_desktop() is not None:
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
if sys.platform == "win32" and winget:
|
|
206
|
+
if typer.confirm("Try installing OpenCode Desktop via winget?", default=True):
|
|
207
|
+
res = subprocess.run([winget, "install", "--id", "SST.opencode", "-e"])
|
|
208
|
+
if res.returncode == 0 and find_opencode_desktop() is not None:
|
|
209
|
+
return True
|
|
210
|
+
|
|
211
|
+
console.print(Panel.fit(
|
|
212
|
+
f"Open [link={OPENCODE_DOWNLOAD_URL}]{OPENCODE_DOWNLOAD_URL}[/link] to download the OpenCode Desktop installer for your OS\n"
|
|
213
|
+
"(.exe/.msi on Windows, .dmg on macOS, .deb/.AppImage on Debian/Ubuntu/Linux).",
|
|
214
|
+
title="OpenCode Desktop Download",
|
|
215
|
+
border_style="cyan",
|
|
216
|
+
))
|
|
217
|
+
if typer.confirm("Open download page in your browser?", default=True):
|
|
218
|
+
webbrowser.open(OPENCODE_DOWNLOAD_URL)
|
|
219
|
+
return find_opencode_desktop() is not None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def prompt_and_install_opencode(cfg, save_fn, *, prefer_desktop: bool = False) -> Optional[bool]:
|
|
223
|
+
"""
|
|
224
|
+
Detect OpenCode; if missing, interactively ask the user whether to install
|
|
225
|
+
OpenCode CLI, OpenCode Desktop, or provide a custom path.
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
True -> launch Desktop
|
|
229
|
+
False -> launch CLI
|
|
230
|
+
None -> user cancelled
|
|
231
|
+
"""
|
|
232
|
+
detected = detect_opencode(cfg)
|
|
233
|
+
has_cli = detected["cli"] is not None
|
|
234
|
+
has_desk = detected["desktop"] is not None
|
|
235
|
+
|
|
236
|
+
if prefer_desktop and has_desk:
|
|
237
|
+
return True
|
|
238
|
+
if not prefer_desktop and has_cli:
|
|
239
|
+
return False
|
|
240
|
+
|
|
241
|
+
# If one is missing but the other exists, offer to use the other or install
|
|
242
|
+
print_detection_table(detected)
|
|
243
|
+
|
|
244
|
+
if not has_cli and not has_desk:
|
|
245
|
+
console.print("[yellow]OpenCode is not installed or not found on PATH.[/yellow]")
|
|
246
|
+
if not typer.confirm("Would you like to install or configure OpenCode now?", default=True):
|
|
247
|
+
return None
|
|
248
|
+
else:
|
|
249
|
+
missing = "Desktop" if prefer_desktop else "CLI"
|
|
250
|
+
other = "CLI" if prefer_desktop else "Desktop"
|
|
251
|
+
console.print(f"[yellow]OpenCode {missing} was not found, but {other} is installed.[/yellow]")
|
|
252
|
+
if typer.confirm(f"Launch OpenCode {other} instead?", default=True):
|
|
253
|
+
return not prefer_desktop
|
|
254
|
+
|
|
255
|
+
console.print("\n[bold]Which OpenCode version do you want?[/bold]")
|
|
256
|
+
console.print(" [bold]1.[/bold] OpenCode CLI (terminal agent)")
|
|
257
|
+
console.print(" [bold]2.[/bold] OpenCode Desktop (GUI app)")
|
|
258
|
+
console.print(" [bold]3.[/bold] Other / Custom binary path")
|
|
259
|
+
console.print(" [bold]4.[/bold] Cancel")
|
|
260
|
+
|
|
261
|
+
choice = typer.prompt("Choose an option [1-4]", default="1").strip()
|
|
262
|
+
|
|
263
|
+
if choice == "1":
|
|
264
|
+
if install_opencode_cli():
|
|
265
|
+
console.print("[green]OpenCode CLI installed successfully.[/green]")
|
|
266
|
+
return False
|
|
267
|
+
return None
|
|
268
|
+
elif choice == "2":
|
|
269
|
+
if install_opencode_desktop():
|
|
270
|
+
console.print("[green]OpenCode Desktop installed successfully.[/green]")
|
|
271
|
+
return True
|
|
272
|
+
console.print("[yellow]Re-run `ocu run --desktop` once Desktop installation finishes.[/yellow]")
|
|
273
|
+
return None
|
|
274
|
+
elif choice == "3":
|
|
275
|
+
custom = typer.prompt("Enter full path to OpenCode binary").strip().strip('"')
|
|
276
|
+
p = Path(custom).expanduser()
|
|
277
|
+
if not p.exists():
|
|
278
|
+
console.print(f"[red]Path does not exist:[/red] {p}")
|
|
279
|
+
return None
|
|
280
|
+
is_desk = typer.confirm("Is this a Desktop GUI app (instead of CLI)?", default=False)
|
|
281
|
+
if is_desk:
|
|
282
|
+
cfg.opencode_desktop_path = str(p)
|
|
283
|
+
else:
|
|
284
|
+
cfg.opencode_cli_path = str(p)
|
|
285
|
+
save_fn(cfg)
|
|
286
|
+
console.print("[green]Saved custom OpenCode path to config.[/green]")
|
|
287
|
+
return is_desk
|
|
288
|
+
else:
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def build_proxy_env(
|
|
293
|
+
proxy_port: int,
|
|
294
|
+
base_env: Optional[Dict[str, str]] = None,
|
|
295
|
+
) -> Dict[str, str]:
|
|
296
|
+
"""Return a copy of the environment configured to route through ZenProxy."""
|
|
297
|
+
env = dict(base_env if base_env is not None else os.environ)
|
|
298
|
+
proxy_url = f"http://127.0.0.1:{proxy_port}"
|
|
299
|
+
env["HTTP_PROXY"] = proxy_url
|
|
300
|
+
env["HTTPS_PROXY"] = proxy_url
|
|
301
|
+
env["ALL_PROXY"] = proxy_url
|
|
302
|
+
env["http_proxy"] = proxy_url
|
|
303
|
+
env["https_proxy"] = proxy_url
|
|
304
|
+
env["all_proxy"] = proxy_url
|
|
305
|
+
env.setdefault("NO_PROXY", "localhost,127.0.0.1,::1")
|
|
306
|
+
env.setdefault("no_proxy", "localhost,127.0.0.1,::1")
|
|
307
|
+
return env
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def launch_opencode(
|
|
311
|
+
proxy_port: int,
|
|
312
|
+
extra_args: Optional[List[str]] = None,
|
|
313
|
+
*,
|
|
314
|
+
desktop: bool = False,
|
|
315
|
+
cfg=None,
|
|
316
|
+
) -> int:
|
|
317
|
+
"""
|
|
318
|
+
Launch OpenCode (CLI in foreground, or Desktop detached) with proxy env vars.
|
|
319
|
+
Returns process exit code (0 on desktop launch).
|
|
320
|
+
"""
|
|
321
|
+
env = build_proxy_env(proxy_port)
|
|
322
|
+
args = list(extra_args or [])
|
|
323
|
+
|
|
324
|
+
if desktop:
|
|
325
|
+
desk_custom = getattr(cfg, "opencode_desktop_path", "") if cfg else ""
|
|
326
|
+
app_path = find_opencode_desktop(desk_custom)
|
|
327
|
+
if app_path is None:
|
|
328
|
+
raise FileNotFoundError(
|
|
329
|
+
"OpenCode Desktop was not found. Install it or omit --desktop to launch the CLI."
|
|
330
|
+
)
|
|
331
|
+
if sys.platform == "darwin" and app_path.suffix == ".app":
|
|
332
|
+
cmd = ["open", "-a", str(app_path)]
|
|
333
|
+
if args:
|
|
334
|
+
cmd += ["--args", *args]
|
|
335
|
+
subprocess.Popen(cmd, env=env, start_new_session=True)
|
|
336
|
+
else:
|
|
337
|
+
kwargs: dict = {"env": env}
|
|
338
|
+
if sys.platform == "win32":
|
|
339
|
+
kwargs["creationflags"] = (
|
|
340
|
+
getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
|
|
341
|
+
| getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
|
|
342
|
+
)
|
|
343
|
+
else:
|
|
344
|
+
kwargs["start_new_session"] = True
|
|
345
|
+
subprocess.Popen([str(app_path), *args], **kwargs)
|
|
346
|
+
return 0
|
|
347
|
+
|
|
348
|
+
cli_custom = getattr(cfg, "opencode_cli_path", "") if cfg else ""
|
|
349
|
+
cli_bin = find_opencode_cli(cli_custom)
|
|
350
|
+
if cli_bin is None:
|
|
351
|
+
raise FileNotFoundError(
|
|
352
|
+
"OpenCode CLI ('opencode') was not found in PATH. "
|
|
353
|
+
"Install OpenCode or pass --desktop to launch OpenCode Desktop."
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
proc = subprocess.run([cli_bin, *with_private_server(args)], env=env)
|
|
357
|
+
return proc.returncode
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def with_private_server(args: List[str]) -> List[str]:
|
|
361
|
+
"""
|
|
362
|
+
Add ``--standalone`` so OpenCode makes its API calls from a process that
|
|
363
|
+
inherits our proxy environment.
|
|
364
|
+
|
|
365
|
+
OpenCode 2.x hands work to a long-lived background service by default.
|
|
366
|
+
That service was started without HTTP(S)_PROXY, so setting the proxy on
|
|
367
|
+
the CLI process alone sent all traffic around ocu (verified with
|
|
368
|
+
opencode v2.0.31: no CONNECT reached the proxy until --standalone).
|
|
369
|
+
|
|
370
|
+
Only the TUI (no subcommand) and ``run`` are changed; other subcommands
|
|
371
|
+
and explicit ``--server`` / ``--standalone`` choices are left as is.
|
|
372
|
+
"""
|
|
373
|
+
if any(a == "--standalone" or a == "--server" or a.startswith("--server=") for a in args):
|
|
374
|
+
return list(args)
|
|
375
|
+
if not args or args[0].startswith("-"):
|
|
376
|
+
return ["--standalone", *args]
|
|
377
|
+
if args[0] == "run":
|
|
378
|
+
return ["run", "--standalone", *args[1:]]
|
|
379
|
+
return list(args)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# pool package
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Account/session pool manager for opencode-unlimited."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import uuid
|
|
8
|
+
from dataclasses import asdict, dataclass, field
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
from rich.text import Text
|
|
15
|
+
|
|
16
|
+
from opencode_unlimited.constants import CONFIG_DIR
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
ACCOUNTS_FILE = CONFIG_DIR / "accounts.json"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Account:
|
|
25
|
+
"""Represents a single OpenCode account/session token."""
|
|
26
|
+
|
|
27
|
+
id: str
|
|
28
|
+
token: str
|
|
29
|
+
active: bool = False
|
|
30
|
+
rate_limited: bool = False
|
|
31
|
+
last_used: Optional[datetime] = None
|
|
32
|
+
|
|
33
|
+
def masked_token(self) -> str:
|
|
34
|
+
"""Return token with middle chars masked."""
|
|
35
|
+
if len(self.token) <= 8:
|
|
36
|
+
return "****"
|
|
37
|
+
return self.token[:4] + "*" * (len(self.token) - 8) + self.token[-4:]
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict:
|
|
40
|
+
return {
|
|
41
|
+
"id": self.id,
|
|
42
|
+
"token": self.token,
|
|
43
|
+
"active": self.active,
|
|
44
|
+
"rate_limited": self.rate_limited,
|
|
45
|
+
"last_used": self.last_used.isoformat() if self.last_used else None,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_dict(cls, data: dict) -> "Account":
|
|
50
|
+
last_used = data.get("last_used")
|
|
51
|
+
if last_used:
|
|
52
|
+
last_used = datetime.fromisoformat(last_used)
|
|
53
|
+
return cls(
|
|
54
|
+
id=data["id"],
|
|
55
|
+
token=data["token"],
|
|
56
|
+
active=data.get("active", False),
|
|
57
|
+
rate_limited=data.get("rate_limited", False),
|
|
58
|
+
last_used=last_used,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AccountPool:
|
|
63
|
+
"""Manages a rotating pool of OpenCode accounts/tokens."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, config_path: Optional[Path] = None) -> None:
|
|
66
|
+
self._accounts: list[Account] = []
|
|
67
|
+
self._config_path = config_path or ACCOUNTS_FILE
|
|
68
|
+
self._active_index: int = 0
|
|
69
|
+
self.load()
|
|
70
|
+
|
|
71
|
+
# ------------------------------------------------------------------
|
|
72
|
+
# Persistence
|
|
73
|
+
# ------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
def load(self) -> None:
|
|
76
|
+
"""Load accounts from JSON file. Creates empty pool if file absent."""
|
|
77
|
+
if not self._config_path.exists():
|
|
78
|
+
logger.debug("No accounts file found at %s; starting empty pool.", self._config_path)
|
|
79
|
+
self._accounts = []
|
|
80
|
+
return
|
|
81
|
+
try:
|
|
82
|
+
raw = self._config_path.read_text(encoding="utf-8")
|
|
83
|
+
data = json.loads(raw)
|
|
84
|
+
self._accounts = [Account.from_dict(a) for a in data.get("accounts", [])]
|
|
85
|
+
self._active_index = data.get("active_index", 0)
|
|
86
|
+
# Clamp index to valid range
|
|
87
|
+
if self._accounts:
|
|
88
|
+
self._active_index = max(0, min(self._active_index, len(self._accounts) - 1))
|
|
89
|
+
logger.info("Loaded %d accounts from %s", len(self._accounts), self._config_path)
|
|
90
|
+
except (json.JSONDecodeError, KeyError, ValueError) as exc:
|
|
91
|
+
logger.error("Failed to load accounts file: %s", exc)
|
|
92
|
+
self._accounts = []
|
|
93
|
+
|
|
94
|
+
def save(self) -> None:
|
|
95
|
+
"""Persist account pool to JSON file."""
|
|
96
|
+
self._config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
payload = {
|
|
98
|
+
"accounts": [a.to_dict() for a in self._accounts],
|
|
99
|
+
"active_index": self._active_index,
|
|
100
|
+
}
|
|
101
|
+
self._config_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
102
|
+
logger.debug("Saved %d accounts to %s", len(self._accounts), self._config_path)
|
|
103
|
+
|
|
104
|
+
# ------------------------------------------------------------------
|
|
105
|
+
# Mutation
|
|
106
|
+
# ------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
def add_account(self, token: str) -> Account:
|
|
109
|
+
"""Add a new account token to the pool."""
|
|
110
|
+
account = Account(id=str(uuid.uuid4()), token=token)
|
|
111
|
+
self._accounts.append(account)
|
|
112
|
+
# Activate it if the pool was previously empty
|
|
113
|
+
if len(self._accounts) == 1:
|
|
114
|
+
account.active = True
|
|
115
|
+
self._active_index = 0
|
|
116
|
+
self.save()
|
|
117
|
+
logger.info("Added account %s to pool", account.id)
|
|
118
|
+
return account
|
|
119
|
+
|
|
120
|
+
def remove_account(self, account_id: str) -> None:
|
|
121
|
+
"""Remove an account by ID."""
|
|
122
|
+
before = len(self._accounts)
|
|
123
|
+
self._accounts = [a for a in self._accounts if a.id != account_id]
|
|
124
|
+
if len(self._accounts) == before:
|
|
125
|
+
raise ValueError(f"Account {account_id!r} not found in pool")
|
|
126
|
+
# Adjust active index
|
|
127
|
+
if self._accounts:
|
|
128
|
+
self._active_index = max(0, min(self._active_index, len(self._accounts) - 1))
|
|
129
|
+
self._accounts[self._active_index].active = True
|
|
130
|
+
else:
|
|
131
|
+
self._active_index = 0
|
|
132
|
+
self.save()
|
|
133
|
+
logger.info("Removed account %s from pool", account_id)
|
|
134
|
+
|
|
135
|
+
def mark_rate_limited(self, account_id: str) -> None:
|
|
136
|
+
"""Mark a specific account as rate-limited."""
|
|
137
|
+
for acc in self._accounts:
|
|
138
|
+
if acc.id == account_id:
|
|
139
|
+
acc.rate_limited = True
|
|
140
|
+
acc.active = False
|
|
141
|
+
logger.warning("Account %s marked as rate-limited", account_id)
|
|
142
|
+
self.save()
|
|
143
|
+
return
|
|
144
|
+
raise ValueError(f"Account {account_id!r} not found")
|
|
145
|
+
|
|
146
|
+
def clear_rate_limits(self) -> None:
|
|
147
|
+
"""Reset rate_limited flag on all accounts."""
|
|
148
|
+
for acc in self._accounts:
|
|
149
|
+
acc.rate_limited = False
|
|
150
|
+
self.save()
|
|
151
|
+
logger.info("Cleared rate limits on all %d accounts", len(self._accounts))
|
|
152
|
+
|
|
153
|
+
# ------------------------------------------------------------------
|
|
154
|
+
# Selection
|
|
155
|
+
# ------------------------------------------------------------------
|
|
156
|
+
|
|
157
|
+
def get_active(self) -> Optional[Account]:
|
|
158
|
+
"""Return the current active, non-rate-limited account."""
|
|
159
|
+
if not self._accounts:
|
|
160
|
+
return None
|
|
161
|
+
# Try current index first
|
|
162
|
+
current = self._accounts[self._active_index]
|
|
163
|
+
if not current.rate_limited:
|
|
164
|
+
return current
|
|
165
|
+
# Walk through pool for any healthy account
|
|
166
|
+
for acc in self._accounts:
|
|
167
|
+
if not acc.rate_limited:
|
|
168
|
+
return acc
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def rotate(self) -> Optional[Account]:
|
|
172
|
+
"""Mark current account as rate-limited and switch to the next healthy one."""
|
|
173
|
+
if not self._accounts:
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
current = self._accounts[self._active_index]
|
|
177
|
+
current.rate_limited = True
|
|
178
|
+
current.active = False
|
|
179
|
+
logger.warning("Rotating away from rate-limited account %s", current.id)
|
|
180
|
+
|
|
181
|
+
# Find next non-rate-limited account
|
|
182
|
+
total = len(self._accounts)
|
|
183
|
+
for offset in range(1, total + 1):
|
|
184
|
+
next_index = (self._active_index + offset) % total
|
|
185
|
+
candidate = self._accounts[next_index]
|
|
186
|
+
if not candidate.rate_limited:
|
|
187
|
+
candidate.active = True
|
|
188
|
+
candidate.last_used = datetime.utcnow()
|
|
189
|
+
self._active_index = next_index
|
|
190
|
+
self.save()
|
|
191
|
+
logger.info("Rotated to account %s", candidate.id)
|
|
192
|
+
return candidate
|
|
193
|
+
|
|
194
|
+
# All accounts are rate-limited
|
|
195
|
+
logger.error("All accounts are rate-limited - cannot rotate")
|
|
196
|
+
self.save()
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
# ------------------------------------------------------------------
|
|
200
|
+
# Display
|
|
201
|
+
# ------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
def status_table(self) -> Table:
|
|
204
|
+
"""Return a rich Table with the current pool status."""
|
|
205
|
+
table = Table(title="Account Pool", show_lines=True)
|
|
206
|
+
table.add_column("ID", style="dim", width=10)
|
|
207
|
+
table.add_column("Token", style="cyan")
|
|
208
|
+
table.add_column("Active", justify="center")
|
|
209
|
+
table.add_column("Rate-Limited", justify="center")
|
|
210
|
+
table.add_column("Last Used", style="dim")
|
|
211
|
+
|
|
212
|
+
if not self._accounts:
|
|
213
|
+
table.add_row("[dim]No accounts configured[/dim]", "", "", "", "")
|
|
214
|
+
return table
|
|
215
|
+
|
|
216
|
+
for acc in self._accounts:
|
|
217
|
+
is_active = not acc.rate_limited and self._accounts.index(acc) == self._active_index
|
|
218
|
+
active_str = Text("YES", style="bold green") if is_active else Text("no", style="dim")
|
|
219
|
+
rl_str = Text("YES", style="bold red") if acc.rate_limited else Text("no", style="green")
|
|
220
|
+
last_used = acc.last_used.strftime("%Y-%m-%d %H:%M:%S") if acc.last_used else "never"
|
|
221
|
+
table.add_row(
|
|
222
|
+
acc.id[:8] + "...",
|
|
223
|
+
acc.masked_token(),
|
|
224
|
+
active_str,
|
|
225
|
+
rl_str,
|
|
226
|
+
last_used,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
return table
|
|
230
|
+
|
|
231
|
+
def __len__(self) -> int:
|
|
232
|
+
return len(self._accounts)
|
|
233
|
+
|
|
234
|
+
def __repr__(self) -> str:
|
|
235
|
+
return f"AccountPool(count={len(self._accounts)}, active_index={self._active_index})"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# opencode_unlimited.proxy
|