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,267 @@
1
+ """
2
+ auto_resume.py - Session auto-resume for opencode-unlimited.
3
+
4
+ Detects when OpenCode has been locked out (rate-limited / session expired)
5
+ and attempts to restore the session automatically.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import List, Optional
16
+
17
+ import httpx
18
+ from rich.console import Console
19
+ from rich.panel import Panel
20
+
21
+ logger = logging.getLogger(__name__)
22
+ console = Console(stderr=True)
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Platform-aware lockout paths
26
+ # ---------------------------------------------------------------------------
27
+
28
+ def _opencode_cache_dirs() -> List[Path]:
29
+ """Return candidate OpenCode config/cache directories for the current OS."""
30
+ dirs: List[Path] = []
31
+
32
+ if sys.platform == "win32":
33
+ appdata = os.environ.get("APPDATA") or os.path.expanduser("~\\AppData\\Roaming")
34
+ localappdata = os.environ.get("LOCALAPPDATA") or os.path.expanduser(
35
+ "~\\AppData\\Local"
36
+ )
37
+ dirs += [
38
+ Path(appdata) / "opencode",
39
+ Path(localappdata) / "opencode",
40
+ ]
41
+ elif sys.platform == "darwin":
42
+ home = Path.home()
43
+ dirs += [
44
+ home / "Library" / "Application Support" / "opencode",
45
+ home / ".config" / "opencode",
46
+ home / ".opencode",
47
+ ]
48
+ else:
49
+ # Linux / other POSIX
50
+ xdg_config = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
51
+ xdg_cache = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
52
+ dirs += [
53
+ Path(xdg_config) / "opencode",
54
+ Path(xdg_cache) / "opencode",
55
+ Path.home() / ".opencode",
56
+ ]
57
+
58
+ return dirs
59
+
60
+
61
+ # Filenames that may indicate a locked-out / stale session state.
62
+ _LOCKOUT_FILENAMES = [
63
+ "lockout",
64
+ "lockout.json",
65
+ "session.lock",
66
+ "rate_limit.json",
67
+ "auth.lock",
68
+ ".session_locked",
69
+ "opencode.lock",
70
+ ]
71
+
72
+ # Local health / status endpoints that OpenCode Desktop or CLI may expose.
73
+ _HEALTH_ENDPOINTS = [
74
+ "http://127.0.0.1:3000/api/health",
75
+ "http://127.0.0.1:3000/health",
76
+ "http://localhost:3000/api/health",
77
+ "http://localhost:3000/health",
78
+ "http://127.0.0.1:7979/health",
79
+ ]
80
+
81
+ # How often (seconds) watch_opencode_state polls for lockout conditions.
82
+ _POLL_INTERVAL_SECONDS = 30
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # AutoResume
87
+ # ---------------------------------------------------------------------------
88
+
89
+
90
+ class AutoResume:
91
+ """
92
+ Detects and clears OpenCode session lockout conditions, then signals the
93
+ local OpenCode process to resume normal operation.
94
+ """
95
+
96
+ def __init__(self, config) -> None:
97
+ """
98
+ Parameters
99
+ ----------
100
+ config:
101
+ An ``OCUConfig`` instance (or any object with an ``auto_resume``
102
+ bool attribute). When ``config.auto_resume`` is *False*, all
103
+ active methods are no-ops.
104
+ """
105
+ self._config = config
106
+ self._last_resume_at: Optional[float] = None
107
+
108
+ # ------------------------------------------------------------------
109
+ # Public async API
110
+ # ------------------------------------------------------------------
111
+
112
+ async def resume(self) -> bool:
113
+ """
114
+ Attempt to resume the OpenCode session.
115
+
116
+ Steps
117
+ -----
118
+ 1. Clear local lockout / cache files.
119
+ 2. Send a request to the local OpenCode health/resume endpoint.
120
+ 3. Log the outcome with a rich panel.
121
+
122
+ Returns
123
+ -------
124
+ bool
125
+ ``True`` if at least the cache was cleared and/or the endpoint
126
+ responded successfully; ``False`` otherwise.
127
+ """
128
+ if not getattr(self._config, "auto_resume", True):
129
+ logger.debug("auto_resume is disabled in config; skipping resume()")
130
+ return False
131
+
132
+ logger.info("AutoResume.resume() triggered")
133
+ success = False
134
+
135
+ # Step 1: Clear lockout files
136
+ cleared = self.clear_lockout_cache()
137
+
138
+ # Step 2: Ping health endpoint
139
+ endpoint_ok = await self._ping_health_endpoints()
140
+
141
+ success = cleared or endpoint_ok
142
+ import time
143
+ self._last_resume_at = time.monotonic()
144
+
145
+ # Step 3: Rich output
146
+ status_color = "green" if success else "yellow"
147
+ status_text = "SUCCESS" if success else "PARTIAL / NO RESPONSE"
148
+ panel_body = (
149
+ f"[bold]Cleared lockout files:[/] {cleared}\n"
150
+ f"[bold]Health endpoint OK:[/] {endpoint_ok}\n"
151
+ f"[bold]Overall status:[/] [{status_color}]{status_text}[/]"
152
+ )
153
+ console.print(
154
+ Panel(
155
+ panel_body,
156
+ title="[bold cyan]AutoResume - Session Restore[/]",
157
+ border_style="cyan",
158
+ expand=False,
159
+ )
160
+ )
161
+ return success
162
+
163
+ async def watch_opencode_state(self, poll_interval: float = _POLL_INTERVAL_SECONDS) -> None:
164
+ """
165
+ Poll OpenCode state indefinitely.
166
+
167
+ When a lockout condition is detected, :meth:`resume` is called
168
+ automatically.
169
+
170
+ Parameters
171
+ ----------
172
+ poll_interval:
173
+ Seconds between state checks.
174
+ """
175
+ logger.info(
176
+ "AutoResume.watch_opencode_state() started (interval=%ss)", poll_interval
177
+ )
178
+ while True:
179
+ try:
180
+ locked = await self.is_locked_out()
181
+ if locked:
182
+ logger.warning("Lockout condition detected, triggering resume()")
183
+ await self.resume()
184
+ else:
185
+ logger.debug("OpenCode session healthy, no lockout detected")
186
+ except Exception as exc: # noqa: BLE001
187
+ logger.error("watch_opencode_state error: %s", exc)
188
+
189
+ await asyncio.sleep(poll_interval)
190
+
191
+ def clear_lockout_cache(self) -> bool:
192
+ """
193
+ Delete known OpenCode cache / lockout files from all candidate
194
+ directories on the current platform.
195
+
196
+ Returns
197
+ -------
198
+ bool
199
+ ``True`` if at least one file was deleted, ``False`` otherwise.
200
+ """
201
+ deleted_any = False
202
+ for base_dir in _opencode_cache_dirs():
203
+ if not base_dir.exists():
204
+ continue
205
+ for filename in _LOCKOUT_FILENAMES:
206
+ target = base_dir / filename
207
+ if target.exists():
208
+ try:
209
+ target.unlink()
210
+ logger.info("Deleted lockout file: %s", target)
211
+ deleted_any = True
212
+ except OSError as exc:
213
+ logger.warning("Could not delete %s: %s", target, exc)
214
+ return deleted_any
215
+
216
+ async def is_locked_out(self) -> bool:
217
+ """
218
+ Determine whether OpenCode is currently locked out.
219
+
220
+ Heuristic
221
+ ---------
222
+ * Returns ``True`` when **any** lockout file exists in a candidate
223
+ cache directory, OR the local health endpoint returns a non-2xx
224
+ status (or is unreachable) AND the process appears to be running.
225
+
226
+ Returns
227
+ -------
228
+ bool
229
+ """
230
+ # Check for lockout files first (fast, local).
231
+ for base_dir in _opencode_cache_dirs():
232
+ if not base_dir.exists():
233
+ continue
234
+ for filename in _LOCKOUT_FILENAMES:
235
+ if (base_dir / filename).exists():
236
+ logger.debug(
237
+ "Lockout file found: %s/%s", base_dir, filename
238
+ )
239
+ return True
240
+
241
+ # An unreachable local health endpoint is NOT treated as a lockout.
242
+ # OpenCode doesn't serve those ports by default, so the old
243
+ # "unreachable + OpenCode dir exists" rule was true on every poll and
244
+ # triggered resume() (which deletes files) every 30 seconds.
245
+ return False
246
+
247
+ # ------------------------------------------------------------------
248
+ # Internal helpers
249
+ # ------------------------------------------------------------------
250
+
251
+ async def _ping_health_endpoints(self) -> bool:
252
+ """
253
+ Try each health endpoint in order; return ``True`` on the first 2xx.
254
+ """
255
+ async with httpx.AsyncClient(timeout=5.0) as client:
256
+ for url in _HEALTH_ENDPOINTS:
257
+ try:
258
+ resp = await client.get(url)
259
+ if resp.is_success:
260
+ logger.debug("Health endpoint OK: %s (%s)", url, resp.status_code)
261
+ return True
262
+ logger.debug(
263
+ "Health endpoint %s returned %s", url, resp.status_code
264
+ )
265
+ except httpx.RequestError as exc:
266
+ logger.debug("Health endpoint %s unreachable: %s", url, exc)
267
+ return False
@@ -0,0 +1,269 @@
1
+ """
2
+ zen_guard.py - Rate-limit watcher for opencode-unlimited.
3
+
4
+ Monitors 429 responses, triggers proxy lane rotation, records events,
5
+ and surfaces status via rich panels.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import re
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Callable, Awaitable, List, Optional
17
+
18
+ from rich.console import Console
19
+ from rich.panel import Panel
20
+ from rich.table import Table
21
+ from rich.text import Text
22
+
23
+ logger = logging.getLogger(__name__)
24
+ console = Console(stderr=True)
25
+
26
+ # Maximum number of rate-limit events to keep in memory.
27
+ _MAX_EVENTS = 200
28
+
29
+ # Regex that matches log lines emitted by aiohttp / httpx when a 429 is seen.
30
+ _PATTERN_429 = re.compile(
31
+ r"(?P<url>https?://\S+).*?429|429.*?(?P<url2>https?://\S+)",
32
+ re.IGNORECASE,
33
+ )
34
+ _RETRY_AFTER_PATTERN = re.compile(r"retry[_-]?after[:\s=]+(?P<sec>\d+)", re.IGNORECASE)
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Data model
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ @dataclass
43
+ class RateLimitEvent:
44
+ """Represents a single 429 rate-limit detection."""
45
+
46
+ timestamp: datetime
47
+ lane: str
48
+ url: str
49
+ retry_after: Optional[int] = None
50
+
51
+ def __str__(self) -> str: # noqa: D105
52
+ ra = f" retry_after={self.retry_after}s" if self.retry_after is not None else ""
53
+ return (
54
+ f"[{self.timestamp.strftime('%H:%M:%S')}] "
55
+ f"lane={self.lane} url={self.url}{ra}"
56
+ )
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # ZenGuard
61
+ # ---------------------------------------------------------------------------
62
+
63
+
64
+ class ZenGuard:
65
+ """
66
+ Watches for HTTP 429 rate-limit conditions, rotates the proxy lane,
67
+ optionally triggers an auto-resume handler, and keeps a rolling log
68
+ of events for status reporting.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ proxy_chain,
74
+ auto_resume_handler: Optional[Callable[[], Awaitable[None]]] = None,
75
+ ) -> None:
76
+ """
77
+ Parameters
78
+ ----------
79
+ proxy_chain:
80
+ An instance of ``ProxyChain``; used to call ``rotate()``.
81
+ auto_resume_handler:
82
+ Optional async callable invoked after every 429 detection.
83
+ Typically ``AutoResume.resume``.
84
+ """
85
+ self._proxy_chain = proxy_chain
86
+ self._auto_resume_handler = auto_resume_handler
87
+ self._events: List[RateLimitEvent] = []
88
+ self._lock = asyncio.Lock()
89
+
90
+ # ------------------------------------------------------------------
91
+ # Core handler
92
+ # ------------------------------------------------------------------
93
+
94
+ async def on_rate_limit(
95
+ self,
96
+ url: str,
97
+ lane: str,
98
+ retry_after: Optional[int] = None,
99
+ rotate: bool = True,
100
+ ) -> None:
101
+ """
102
+ Called by the proxy when a 429 response is detected.
103
+
104
+ 1. Logs a rich warning panel.
105
+ 2. Rotates the proxy lane (skipped when ``rotate=False``, used when
106
+ the caller such as ZenProxy already owns rotation).
107
+ 3. Invokes auto_resume_handler when configured.
108
+ 4. Records the event.
109
+ """
110
+ event = RateLimitEvent(
111
+ timestamp=datetime.now(tz=timezone.utc),
112
+ lane=lane,
113
+ url=url,
114
+ retry_after=retry_after,
115
+ )
116
+
117
+ # Rich warning panel
118
+ body_lines: List[str] = [
119
+ f"[bold yellow]URL:[/] {url}",
120
+ f"[bold yellow]Lane:[/] {lane}",
121
+ ]
122
+ if retry_after is not None:
123
+ body_lines.append(f"[bold yellow]Retry-After:[/] {retry_after}s")
124
+ body_lines.append(f"[bold yellow]Time:[/] {event.timestamp.isoformat()}")
125
+
126
+ panel = Panel(
127
+ "\n".join(body_lines),
128
+ title="[bold red]429 Rate Limit Detected[/]",
129
+ border_style="red",
130
+ expand=False,
131
+ )
132
+ console.print(panel)
133
+ logger.warning(
134
+ "429 rate-limit on lane=%s url=%s retry_after=%s",
135
+ lane,
136
+ url,
137
+ retry_after,
138
+ )
139
+
140
+ # Rotate lane
141
+ if rotate:
142
+ try:
143
+ self._proxy_chain.rotate()
144
+ logger.info("Proxy lane rotated to: %s", self._proxy_chain.current_lane)
145
+ except Exception as exc: # noqa: BLE001
146
+ logger.error("Lane rotation failed: %s", exc)
147
+
148
+ # Auto-resume handler
149
+ if self._auto_resume_handler is not None:
150
+ try:
151
+ await self._auto_resume_handler()
152
+ except Exception as exc: # noqa: BLE001
153
+ logger.error("auto_resume_handler raised: %s", exc)
154
+
155
+ # Record event (thread-safe under asyncio lock)
156
+ async with self._lock:
157
+ self._events.append(event)
158
+ if len(self._events) > _MAX_EVENTS:
159
+ self._events = self._events[-_MAX_EVENTS:]
160
+
161
+ # ------------------------------------------------------------------
162
+ # Event accessors
163
+ # ------------------------------------------------------------------
164
+
165
+ def get_events(self) -> List[RateLimitEvent]:
166
+ """Return a snapshot of recent :class:`RateLimitEvent` objects."""
167
+ return list(self._events)
168
+
169
+ def clear_events(self) -> None:
170
+ """Discard all recorded rate-limit events."""
171
+ self._events.clear()
172
+
173
+ # ------------------------------------------------------------------
174
+ # Log-file watcher
175
+ # ------------------------------------------------------------------
176
+
177
+ async def watch_log_file(self, log_path: str | Path, poll_interval: float = 1.0) -> None:
178
+ """
179
+ Tail *log_path* indefinitely, calling :meth:`on_rate_limit` whenever
180
+ a line matching a 429 pattern is found.
181
+
182
+ Parameters
183
+ ----------
184
+ log_path:
185
+ Absolute or relative path to the log file to tail.
186
+ poll_interval:
187
+ Seconds to sleep between read attempts when no new data is available.
188
+ """
189
+ log_path = Path(log_path)
190
+ logger.info("ZenGuard watching log file: %s", log_path)
191
+
192
+ # Wait for the file to exist
193
+ while not log_path.exists():
194
+ logger.debug("Log file not yet present, waiting: %s", log_path)
195
+ await asyncio.sleep(poll_interval)
196
+
197
+ try:
198
+ current_lane = str(self._proxy_chain.current_lane)
199
+ except Exception: # noqa: BLE001
200
+ current_lane = "UNKNOWN"
201
+
202
+ with log_path.open("r", encoding="utf-8", errors="replace") as fh:
203
+ # Seek to end so we only process new lines.
204
+ fh.seek(0, 2)
205
+ while True:
206
+ line = fh.readline()
207
+ if not line:
208
+ await asyncio.sleep(poll_interval)
209
+ continue
210
+
211
+ # Update lane snapshot from live proxy_chain.
212
+ try:
213
+ current_lane = str(self._proxy_chain.current_lane)
214
+ except Exception: # noqa: BLE001
215
+ pass
216
+
217
+ m = _PATTERN_429.search(line)
218
+ if m:
219
+ url = m.group("url") or m.group("url2") or "unknown"
220
+ retry_after: Optional[int] = None
221
+ rm = _RETRY_AFTER_PATTERN.search(line)
222
+ if rm:
223
+ retry_after = int(rm.group("sec"))
224
+ await self.on_rate_limit(url=url, lane=current_lane, retry_after=retry_after)
225
+
226
+ # ------------------------------------------------------------------
227
+ # Status panel
228
+ # ------------------------------------------------------------------
229
+
230
+ def status_panel(self, n: int = 10) -> Panel:
231
+ """
232
+ Build and return a :class:`rich.panel.Panel` showing the last *n*
233
+ rate-limit events.
234
+
235
+ Parameters
236
+ ----------
237
+ n:
238
+ Maximum number of events to display (most recent first).
239
+ """
240
+ events = self._events[-n:][::-1] # most recent first
241
+
242
+ table = Table(
243
+ "Time (UTC)",
244
+ "Lane",
245
+ "URL",
246
+ "Retry-After",
247
+ show_header=True,
248
+ header_style="bold cyan",
249
+ expand=True,
250
+ )
251
+
252
+ if not events:
253
+ table.add_row("[dim]No events recorded[/]", "", "", "")
254
+ else:
255
+ for ev in events:
256
+ ra_str = f"{ev.retry_after}s" if ev.retry_after is not None else "-"
257
+ table.add_row(
258
+ ev.timestamp.strftime("%H:%M:%S"),
259
+ ev.lane,
260
+ Text(ev.url, overflow="fold"),
261
+ ra_str,
262
+ )
263
+
264
+ return Panel(
265
+ table,
266
+ title=f"[bold green]ZenGuard - Rate Limit Events (last {n})[/]",
267
+ border_style="green",
268
+ expand=False,
269
+ )