"""Bridge between FastAPI and Claude Code CLI subprocess.""" import asyncio import json import os from pathlib import Path from typing import AsyncGenerator CLAUDE_BIN = os.environ.get( "CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude") ) DATA_DIR = Path(os.environ.get("DATA_DIR", "/tmp/smeta-web-data")) APP_DIR = Path(__file__).parent # Session tracking: tab_id -> claude session_id _sessions: dict[str, str] = {} def get_work_dir(username: str, tab_id: str) -> Path: d = DATA_DIR / username / tab_id d.mkdir(parents=True, exist_ok=True) return d def get_session_id(tab_id: str) -> str | None: return _sessions.get(tab_id) def set_session_id(tab_id: str, sid: str): _sessions[tab_id] = sid def clear_session(tab_id: str): _sessions.pop(tab_id, None) async def stream_claude( message: str, username: str, tab_id: str = "default", ) -> AsyncGenerator[str, None]: """Run claude CLI, yield SSE-formatted events.""" work_dir = get_work_dir(username, tab_id) session_id = get_session_id(tab_id) instructions = APP_DIR / "claude_project_instructions.md" cmd = [ CLAUDE_BIN, "-p", message, "--output-format", "stream-json", "--verbose", "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep", ] if instructions.exists(): cmd.extend(["--append-system-prompt-file", str(instructions)]) if session_id: cmd.extend(["--resume", session_id]) env = os.environ.copy() # Proxy for Anthropic API (xray on server) env.setdefault("HTTPS_PROXY", "http://127.0.0.1:10809") env.setdefault("HTTP_PROXY", "http://127.0.0.1:10809") proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=str(work_dir), env=env, ) try: async for raw_line in proc.stdout: line = raw_line.decode().strip() if not line: continue try: event = json.loads(line) except json.JSONDecodeError: continue etype = event.get("type", "") if etype == "assistant": # Extract text from content blocks msg = event.get("message", {}) for block in msg.get("content", []): if block.get("type") == "text": text = block["text"] yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" elif block.get("type") == "tool_use": name = block.get("name", "") inp = block.get("input", {}) yield f"event: tool\ndata: {json.dumps({'tool': name, 'input': inp}, ensure_ascii=False)}\n\n" elif etype == "result": sid = event.get("session_id", "") if sid: set_session_id(tab_id, sid) result_text = event.get("result", "") cost = event.get("total_cost_usd", 0) yield f"event: done\ndata: {json.dumps({'result': result_text, 'cost': cost}, ensure_ascii=False)}\n\n" finally: if proc.returncode is None: proc.terminate() await proc.wait() def list_user_files(username: str, tab_id: str = "default") -> list[dict]: """List files in user's work directory.""" work_dir = get_work_dir(username, tab_id) files = [] for f in sorted(work_dir.iterdir()): if f.is_file() and not f.name.startswith("."): files.append({ "name": f.name, "size": f.stat().st_size, }) return files