|
21 | 21 | from pathlib import Path |
22 | 22 | from typing import Any, Dict, List, Literal, Optional |
23 | 23 |
|
24 | | -from fastapi import APIRouter, HTTPException |
| 24 | +from fastapi import APIRouter, HTTPException, Query |
25 | 25 | from pydantic import BaseModel, Field |
26 | 26 |
|
27 | 27 | from paperbot.application.collaboration.message_schema import new_run_id |
@@ -153,6 +153,125 @@ async def start_smoke(body: SmokeRequest) -> SmokeStartResponse: |
153 | 153 | return SmokeStartResponse(run_id=run_id, status="running") |
154 | 154 |
|
155 | 155 |
|
| 156 | +@router.get("/runbook/files") |
| 157 | +async def list_project_files( |
| 158 | + project_dir: str = Query(..., description="Project directory on the API host"), |
| 159 | + recursive: bool = Query(True, description="List files recursively"), |
| 160 | + max_files: int = Query(2000, ge=1, le=20000), |
| 161 | +): |
| 162 | + """ |
| 163 | + List files under a project directory (best-effort). |
| 164 | +
|
| 165 | + Notes: |
| 166 | + - This endpoint is intentionally restrictive and will only serve allowed roots. |
| 167 | + - Large directories (e.g. node_modules) are skipped by default. |
| 168 | + """ |
| 169 | + root = Path(project_dir) |
| 170 | + if not root.exists() or not root.is_dir(): |
| 171 | + raise HTTPException(status_code=400, detail="project_dir must be an existing directory") |
| 172 | + if not _allowed_workdir(root): |
| 173 | + raise HTTPException(status_code=403, detail="project_dir is not allowed") |
| 174 | + |
| 175 | + ignore_dirs = {".git", ".next", "node_modules", ".venv", "__pycache__", ".pytest_cache", ".mypy_cache"} |
| 176 | + |
| 177 | + files: List[str] = [] |
| 178 | + directories: List[str] = [] |
| 179 | + |
| 180 | + if not recursive: |
| 181 | + for p in root.iterdir(): |
| 182 | + if p.is_dir(): |
| 183 | + directories.append(p.name) |
| 184 | + elif p.is_file(): |
| 185 | + files.append(p.name) |
| 186 | + return {"project_dir": str(root), "files": sorted(files), "directories": sorted(directories)} |
| 187 | + |
| 188 | + for dirpath, dirnames, filenames in os.walk(root): |
| 189 | + # prune |
| 190 | + dirnames[:] = [d for d in dirnames if d not in ignore_dirs] |
| 191 | + rel_dir = os.path.relpath(dirpath, root) |
| 192 | + if rel_dir != ".": |
| 193 | + directories.append(rel_dir) |
| 194 | + |
| 195 | + for name in filenames: |
| 196 | + if len(files) >= max_files: |
| 197 | + break |
| 198 | + rel = os.path.relpath(os.path.join(dirpath, name), root) |
| 199 | + files.append(rel) |
| 200 | + if len(files) >= max_files: |
| 201 | + break |
| 202 | + |
| 203 | + return { |
| 204 | + "project_dir": str(root), |
| 205 | + "files": sorted(files), |
| 206 | + "directories": sorted(set(directories)), |
| 207 | + "truncated": len(files) >= max_files, |
| 208 | + "max_files": max_files, |
| 209 | + } |
| 210 | + |
| 211 | + |
| 212 | +class ReadFileResponse(BaseModel): |
| 213 | + path: str |
| 214 | + content: str |
| 215 | + |
| 216 | + |
| 217 | +@router.get("/runbook/file", response_model=ReadFileResponse) |
| 218 | +async def read_project_file( |
| 219 | + project_dir: str = Query(..., description="Project directory on the API host"), |
| 220 | + path: str = Query(..., description="Relative file path within project_dir"), |
| 221 | + max_bytes: int = Query(2_000_000, ge=1, le=20_000_000), |
| 222 | +): |
| 223 | + """Read a single file under project_dir (UTF-8 best effort).""" |
| 224 | + root = Path(project_dir) |
| 225 | + if not root.exists() or not root.is_dir(): |
| 226 | + raise HTTPException(status_code=400, detail="project_dir must be an existing directory") |
| 227 | + if not _allowed_workdir(root): |
| 228 | + raise HTTPException(status_code=403, detail="project_dir is not allowed") |
| 229 | + |
| 230 | + target = (root / path).resolve() |
| 231 | + root_resolved = root.resolve() |
| 232 | + if not (target == root_resolved or str(target).startswith(str(root_resolved) + os.sep)): |
| 233 | + raise HTTPException(status_code=400, detail="invalid path") |
| 234 | + if not target.exists() or not target.is_file(): |
| 235 | + raise HTTPException(status_code=404, detail="file not found") |
| 236 | + |
| 237 | + size = target.stat().st_size |
| 238 | + if size > max_bytes: |
| 239 | + raise HTTPException(status_code=413, detail=f"file too large ({size} bytes)") |
| 240 | + |
| 241 | + try: |
| 242 | + content = target.read_text(encoding="utf-8") |
| 243 | + except Exception: |
| 244 | + content = target.read_text(errors="ignore") |
| 245 | + |
| 246 | + return ReadFileResponse(path=path, content=content) |
| 247 | + |
| 248 | + |
| 249 | +class WriteFileRequest(BaseModel): |
| 250 | + project_dir: str |
| 251 | + path: str |
| 252 | + content: str |
| 253 | + |
| 254 | + |
| 255 | +@router.post("/runbook/file") |
| 256 | +async def write_project_file(body: WriteFileRequest): |
| 257 | + """Write a file under project_dir (creates parents).""" |
| 258 | + root = Path(body.project_dir) |
| 259 | + if not root.exists() or not root.is_dir(): |
| 260 | + raise HTTPException(status_code=400, detail="project_dir must be an existing directory") |
| 261 | + if not _allowed_workdir(root): |
| 262 | + raise HTTPException(status_code=403, detail="project_dir is not allowed") |
| 263 | + |
| 264 | + target = (root / body.path).resolve() |
| 265 | + root_resolved = root.resolve() |
| 266 | + if not (target == root_resolved or str(target).startswith(str(root_resolved) + os.sep)): |
| 267 | + raise HTTPException(status_code=400, detail="invalid path") |
| 268 | + |
| 269 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 270 | + target.write_text(body.content, encoding="utf-8") |
| 271 | + |
| 272 | + return {"ok": True, "path": body.path} |
| 273 | + |
| 274 | + |
156 | 275 | @router.get("/runbook/runs/{run_id}", response_model=RunStatusResponse) |
157 | 276 | async def get_run_status(run_id: str) -> RunStatusResponse: |
158 | 277 | with _provider.session() as session: |
|
0 commit comments