LINE1 10 20 30 40 50 60 70 801#!/usr/bin/env python32"""List sessions currently running on the shared OpenCode service."""34from __future__ import annotations56import argparse7import json8import subprocess9import sys10import time11from concurrent.futures import ThreadPoolExecutor12from pathlib import Path13from typing import Any141516def api_get(path: str) -> dict[str, Any]:17 try:18 result = subprocess.run(19 ["opencode", "api", "get", path],20 check=False,21 capture_output=True,22 text=True,23 timeout=30,24 )25 except FileNotFoundError as error:26 raise RuntimeError("OpenCode CLI was not found on PATH") from error27 except subprocess.TimeoutExpired as error:28 raise RuntimeError(f"OpenCode API request timed out: {path}") from error2930 if result.returncode != 0:31 message = result.stderr.strip() or f"OpenCode API request failed: {path}"32 raise RuntimeError(message)3334 try:35 payload = json.loads(result.stdout)36 except json.JSONDecodeError as error:37 raise RuntimeError(f"OpenCode returned invalid JSON for {path}") from error3839 if not isinstance(payload, dict):40 raise RuntimeError(f"Unexpected OpenCode API response for {path}")41 return payload424344def active_sessions() -> list[dict[str, Any]]:45 response = api_get("/api/session/active")46 active = response.get("data", {})47 if not isinstance(active, dict):48 raise RuntimeError("Unexpected active-sessions response")4950 session_ids = list(active)51 if not session_ids:52 return []5354 def fetch_session(session_id: str) -> dict[str, Any] | None:55 try:56 response = api_get(f"/api/session/{session_id}")57 except RuntimeError as error:58 print(f"warning: could not inspect {session_id}: {error}", file=sys.stderr)59 return None60 session = response.get("data")61 if not isinstance(session, dict):62 return None63 session["status"] = active[session_id].get("type", "running")64 return session6566 with ThreadPoolExecutor(max_workers=min(8, len(session_ids))) as executor:67 sessions = list(executor.map(fetch_session, session_ids))6869 return sorted(70 (session for session in sessions if session is not None),71 key=lambda session: session.get("time", {}).get("created", 0),72 reverse=True,73 )747576def display(sessions: list[dict[str, Any]]) -> None:77 if not sessions:78 print("No sessions are running.")79 return8081 print(f"{len(sessions)} running session(s):")82 for session in sessions:83 session_id = session.get("id", "unknown")84 title = session.get("title", "Untitled session")85 directory = session.get("location", {}).get("directory", "unknown directory")86 print(f"\n{session_id} [{session.get('status', 'running')}] {title}")87 print(f" {Path(directory)}")888990def main() -> int:91 parser = argparse.ArgumentParser(92 description="Show sessions currently running across the shared OpenCode service."93 )94 parser.add_argument(95 "--json",96 action="store_true",97 help="print session details as JSON",98 )99 parser.add_argument(100 "--watch",101 type=float,102 metavar="SECONDS",103 help="refresh repeatedly at this interval",104 )105 args = parser.parse_args()106107 if args.watch is not None and args.watch <= 0:108 parser.error("--watch interval must be greater than zero")109110 try:111 while True:112 sessions = active_sessions()113 if args.json:114 print(json.dumps(sessions, indent=2), flush=True)115 else:116 if args.watch is not None and sys.stdout.isatty():117 print("\033[2J\033[H", end="")118 display(sessions)119 sys.stdout.flush()120121 if args.watch is None:122 return 0123 time.sleep(args.watch)124 except KeyboardInterrupt:125 return 130126 except RuntimeError as error:127 print(f"sessions: {error}", file=sys.stderr)128 return 1129130131if __name__ == "__main__":132 raise SystemExit(main())