"""Auto-Resume module for openhop. Automatically detects when a rate limit is bypassed, clears client-side database lockouts (free-limit / go-upsell), reloads the OpenCode interface, and dispatches a 'continue' action to the active OpenCode session so the model keeps generating autonomously. """ from __future__ import annotations import os import re import sqlite3 import subprocess import sys import time from pathlib import Path _SRC = Path(__file__).resolve().parent if str(_SRC) not in sys.path: sys.path.insert(0, str(_SRC)) from ouc_common import LANE_DIR, find_opencode_cli AUTO_RESUME_FLAG = LANE_DIR / "auto_resume.flag" def is_auto_resume_enabled() -> bool: """Return True if auto-resume is enabled (default is enabled).""" if AUTO_RESUME_FLAG.is_file(): try: return AUTO_RESUME_FLAG.read_text(encoding="utf-8").strip() != "0" except Exception: return True return True def set_auto_resume(enable: bool) -> None: """Enable or disable the auto-resume feature.""" LANE_DIR.mkdir(parents=True, exist_ok=True) AUTO_RESUME_FLAG.write_text("1\n" if enable else "0\n", encoding="utf-8") def clear_opencode_free_limit() -> int: """Delete client-side free-limit and go-upsell lockout rows from drafts.sqlite. OpenCode Desktop stores rate limit timestamps in drafts.sqlite (table 'state'). Even after IP rotation, the UI blocks user prompts until this timestamp is purged. """ candidates = [ Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) / "ai.opencode.desktop" / "drafts.sqlite", Path.home() / ".config" / "ai.opencode.desktop" / "drafts.sqlite", Path.home() / ".local" / "share" / "opencode" / "drafts.sqlite", ] deleted = 0 for db_path in candidates: if not db_path.is_file(): continue try: conn = sqlite3.connect(str(db_path), timeout=3.0) cur = conn.cursor() cur.execute("DELETE FROM state WHERE key IN ('free-limit', 'go-upsell') OR key LIKE '%free%limit%' OR key LIKE '%quota%exceeded%' OR key LIKE '%upsell%'") deleted += cur.rowcount conn.commit() conn.close() except Exception: pass return deleted def get_latest_session_info() -> tuple[str, str, str] | None: """Query opencode.db for the most recently active non-archived session. Returns (session_id, directory, title) or None. """ db_path = Path.home() / ".local" / "share" / "opencode" / "opencode.db" if not db_path.is_file(): return None try: conn = sqlite3.connect(str(db_path), timeout=3.0) cur = conn.cursor() cur.execute( "SELECT id, directory, title FROM session_v2 " "WHERE time_archived IS NULL " "ORDER BY time_updated DESC LIMIT 1" ) row = cur.fetchone() conn.close() if row and row[0]: return str(row[0]), str(row[1] or ""), str(row[2] or "") except Exception: pass return None def send_continue_keystroke(reload_first: bool = True) -> bool: """Send reload (^r) and 'continue{ENTER}' to active OpenCode Desktop or Terminal window.""" if sys.platform != "win32": try: import shutil if shutil.which("xdotool"): if reload_first: subprocess.run(["xdotool", "search", "--onlyvisible", "--class", "opencode", "key", "--clearmodifiers", "ctrl+r"], capture_output=True, timeout=2.0) time.sleep(1.2) subprocess.run(["xdotool", "search", "--onlyvisible", "--class", "opencode", "type", "--clearmodifiers", "continue"], capture_output=True, timeout=2.0) subprocess.run(["xdotool", "search", "--onlyvisible", "--class", "opencode", "key", "--clearmodifiers", "Return"], capture_output=True, timeout=2.0) return True except Exception: pass return False # 1. Native Windows Win32 API window focus and key dispatch try: import ctypes from ctypes import wintypes user32 = ctypes.windll.user32 target_hwnds = [] def _enum_cb(hwnd, _): if user32.IsWindowVisible(hwnd): length = user32.GetWindowTextLengthW(hwnd) buf = ctypes.create_unicode_buffer(length + 1) user32.GetWindowTextW(hwnd, buf, length + 1) title = buf.value.lower() pid = wintypes.DWORD() user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) pname = "" try: import psutil pname = psutil.Process(pid.value).name().lower() except Exception: pass if "opencode" in pname or "opencode" in title: target_hwnds.append((hwnd, buf.value, pname)) return True CB_TYPE = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM) user32.EnumWindows(CB_TYPE(_enum_cb), 0) for hwnd, title, pname in target_hwnds: # SW_RESTORE = 9 user32.ShowWindow(hwnd, 9) user32.SetForegroundWindow(hwnd) time.sleep(0.3) # If requested, send Ctrl+R to reload UI (reloading drops the free-limit block screen) if reload_first and ("desktop" in pname or "opencode.exe" in pname): ps_reload = """ Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.SendKeys]::SendWait("^r") """ subprocess.run( ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps_reload], capture_output=True, creationflags=0x08000000, timeout=3.0, ) time.sleep(1.2) ps_send = """ Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.SendKeys]::SendWait("continue{ENTER}") """ subprocess.run( ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps_send], capture_output=True, creationflags=0x08000000, timeout=4.0, ) return True except Exception: pass # 2. PowerShell WScript.Shell AppActivate fallback ps = """ $ws = New-Object -ComObject WScript.Shell $targets = @("OpenCode", "opencode", "ai.opencode") $sent = $false foreach ($t in $targets) { if ($ws.AppActivate($t)) { Start-Sleep -Milliseconds 300 $ws.SendKeys("^r") Start-Sleep -Milliseconds 1200 $ws.SendKeys("continue{ENTER}") $sent = $true break } } if ($sent) { Write-Output "SENT" } else { Write-Output "NOT_FOUND" } """ try: CREATE_NO_WINDOW = 0x08000000 res = subprocess.run( ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps], capture_output=True, text=True, errors="replace", timeout=5.0, creationflags=CREATE_NO_WINDOW, ) return "SENT" in res.stdout except Exception: return False _SESSION_ID_RE = re.compile(r"\bsessionID=(ses_[A-Za-z0-9]+)") def session_id_in(line: str) -> str: """The OpenCode session a log line belongs to ('' if none). Wall errors carry 'sessionID=ses_…'.""" m = _SESSION_ID_RE.search(line or "") return m.group(1) if m else "" def _session_directory(session_id: str) -> str: db_path = Path.home() / ".local" / "share" / "opencode" / "opencode.db" try: conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=3.0) try: row = conn.execute("SELECT directory FROM session_v2 WHERE id = ?", (session_id,)).fetchone() finally: conn.close() return str(row[0] or "") if row else "" except Exception: return "" def _stop_stale_continue(oc: str, session_id: str) -> None: """A 'continue' we sent earlier to this session that is still hanging around would pile up; end it.""" try: import psutil exe_name = Path(oc).name.lower() for p in psutil.process_iter(["name", "cmdline"]): try: cmd = p.info.get("cmdline") or [] if (p.info.get("name") or "").lower() == exe_name and "run" in cmd and session_id in cmd \ and cmd[-1:] == ["continue"]: p.kill() except Exception: pass except Exception: pass def resume_sessions(session_ids: list[str]) -> tuple[int, list[str]]: """Send 'continue' to each listed session through OpenCode's background service. 'opencode run --session ' talks to the same background service OpenCode Desktop uses, so every tab that hit the limit carries on (not just the one in front), and the Desktop window updates by itself. """ oc = find_opencode_cli() if not oc: return 0, ["OpenCode CLI not found"] sent, notes = 0, [] for sid in dict.fromkeys(s for s in session_ids if s): # unique, keep order directory = _session_directory(sid) cwd = directory if (directory and os.path.isdir(directory)) else None _stop_stale_continue(oc, sid) try: kwargs = {"cwd": cwd, "close_fds": True} if sys.platform == "win32": kwargs["creationflags"] = 0x08000000 | 0x00000008 else: kwargs["start_new_session"] = True subprocess.Popen([oc, "run", "--session", sid, "continue"], **kwargs) sent += 1 except Exception as exc: notes.append(f"{sid[:12]}…: {exc}") return sent, notes def resume_active_session(session_ids: list[str] | None = None) -> tuple[bool, str]: """Resume OpenCode after a new IP: every session in session_ids, or the latest one if none are known.""" if not is_auto_resume_enabled(): return False, "Auto-resume is disabled." # Step 1: Wipe client-side rate limit lockouts from drafts.sqlite cleared = clear_opencode_free_limit() details = [] if cleared > 0: details.append(f"cleared {cleared} rate limit entries from database") if session_ids: sent, notes = resume_sessions(session_ids) details.append(f"sent 'continue' to {sent} of {len(set(session_ids))} chat(s) that hit the limit") details.extend(notes) if sent: return True, " ✓ ".join(details) # nothing could be sent that way: fall through to the old behaviour oc = find_opencode_cli() sess = get_latest_session_info() cli_dispatched = False # Step 2: Attempt CLI session resume if a session exists if oc and sess: sess_id, directory, title = sess cmd = [oc, "run", "--session", sess_id, "continue"] cwd = directory if (directory and os.path.isdir(directory)) else None try: kwargs = {"cwd": cwd, "close_fds": True} if sys.platform == "win32": kwargs["creationflags"] = 0x08000000 | 0x00000008 else: kwargs["start_new_session"] = True subprocess.Popen(cmd, **kwargs) cli_dispatched = True details.append(f"dispatched CLI resume to session {sess_id[:8]}... ({title or 'active'})") except Exception as exc: details.append(f"CLI resume attempt failed: {exc}") elif oc: try: kwargs = {"close_fds": True} if sys.platform == "win32": kwargs["creationflags"] = 0x08000000 | 0x00000008 else: kwargs["start_new_session"] = True subprocess.Popen([oc, "run", "--continue", "continue"], **kwargs) cli_dispatched = True details.append("dispatched generic CLI continue") except Exception: pass # Step 3: Also send keystroke to any interactive OpenCode GUI or terminal window win_sent = send_continue_keystroke(reload_first=True) if win_sent: details.append("sent reload & keystroke 'continue' to active OpenCode window") if cli_dispatched or win_sent or cleared > 0: return True, " ✓ ".join(details) return False, "No active session or window found to resume."