kacapower commited on
Commit
62122e0
·
1 Parent(s): a1efd54

Deploy password-protected OpenCode bridge with 05:30 AM IST daily rolling PIN and bucket persistence

Browse files
Files changed (8) hide show
  1. .gitignore +6 -0
  2. Dockerfile +15 -9
  3. README.md +7 -2
  4. app.py +700 -0
  5. requirements.txt +7 -3
  6. shell.html +455 -0
  7. start.sh +28 -3
  8. sync.py +157 -103
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ .venv/
5
+ env/
6
+ .DS_Store
Dockerfile CHANGED
@@ -1,6 +1,5 @@
1
  FROM node:20-bookworm-slim
2
 
3
- # System dependencies including Python for the sync script
4
  RUN apt-get update && apt-get install -y --no-install-recommends \
5
  git \
6
  ca-certificates \
@@ -9,24 +8,31 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
9
  python3-pip \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
- RUN npm install -g opencode-ai
 
13
 
14
- # Install HF Hub for data synchronization
15
- RUN pip3 install huggingface_hub --break-system-packages
16
 
17
  ENV HOME=/home/node
 
18
  ENV PATH=/home/node/.local/bin:/usr/local/bin:${PATH}
19
 
20
  RUN mkdir -p $HOME/workspace && chown -R node:node $HOME
21
 
22
- # Copy the custom logic files into the container
23
- COPY sync.py $HOME/sync.py
24
- COPY start.sh $HOME/start.sh
25
- RUN chown node:node $HOME/sync.py $HOME/start.sh && chmod +x $HOME/start.sh
 
 
26
 
27
  USER node
28
  WORKDIR $HOME/workspace
29
 
30
- EXPOSE 4096
 
 
 
31
 
32
  CMD ["/home/node/start.sh"]
 
1
  FROM node:20-bookworm-slim
2
 
 
3
  RUN apt-get update && apt-get install -y --no-install-recommends \
4
  git \
5
  ca-certificates \
 
8
  python3-pip \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
+ ARG OPENCODE_VERSION=latest
12
+ RUN npm install -g "opencode-ai@${OPENCODE_VERSION}"
13
 
14
+ COPY requirements.txt /tmp/requirements.txt
15
+ RUN pip3 install --no-cache-dir --break-system-packages -r /tmp/requirements.txt
16
 
17
  ENV HOME=/home/node
18
+ ENV PYTHONUNBUFFERED=1
19
  ENV PATH=/home/node/.local/bin:/usr/local/bin:${PATH}
20
 
21
  RUN mkdir -p $HOME/workspace && chown -R node:node $HOME
22
 
23
+ COPY app.py $HOME/app.py
24
+ COPY shell.html $HOME/shell.html
25
+ COPY sync.py $HOME/sync.py
26
+ COPY start.sh $HOME/start.sh
27
+ RUN chown node:node $HOME/app.py $HOME/shell.html $HOME/sync.py $HOME/start.sh \
28
+ && chmod +x $HOME/start.sh
29
 
30
  USER node
31
  WORKDIR $HOME/workspace
32
 
33
+ EXPOSE 7860
34
+
35
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
36
+ CMD curl -fsS http://127.0.0.1:7860/__health >/dev/null || exit 1
37
 
38
  CMD ["/home/node/start.sh"]
README.md CHANGED
@@ -4,5 +4,10 @@ emoji: 🚀
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
7
- app_port: 4096
8
- ---
 
 
 
 
 
 
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ # OpenCode Protected Space
11
+
12
+ Secure OpenCode proxy protected by dynamic 8-digit daily authentication and HF READ token authorization.
13
+ Connected to persistent private storage bucket `kacapower/ghar-storage`.
app.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenCode Shell & Reverse Proxy for Hugging Face Space.
2
+
3
+ Features:
4
+ - Strict Zero-Access Gatekeeper: Blocks public crawlers and unauthenticated visitors.
5
+ - Dual-layer security:
6
+ * Dynamic 8-digit PIN generated daily at 05:30 AM IST (00:00:00 UTC) using UNLOCK_SECRET.
7
+ * Hugging Face READ token authorization for external web app / API calls.
8
+ - CORS enabled for custom frontend (e.g. allen.site.je).
9
+ - Direct Session Detection: Automatically detects direct HF Space usage.
10
+ - File upload support up to 50MB.
11
+ - Chat session listing & switching API.
12
+ - Model selection and configuration API.
13
+ - Full streaming and WebSocket proxying to local opencode server (127.0.0.1:4096).
14
+ """
15
+
16
+ import asyncio
17
+ import hashlib
18
+ import hmac
19
+ import json
20
+ import os
21
+ import time
22
+ import zipfile
23
+ from datetime import datetime, timezone, timedelta
24
+ from io import BytesIO
25
+ from pathlib import Path
26
+ from typing import Optional
27
+
28
+ import httpx
29
+ from fastapi import FastAPI, File, HTTPException, Header, Query, Request, Response, UploadFile, WebSocket, WebSocketDisconnect
30
+ from fastapi.middleware.cors import CORSMiddleware
31
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
32
+ from starlette.background import BackgroundTask
33
+
34
+ try:
35
+ import websockets
36
+ except ImportError:
37
+ websockets = None
38
+
39
+ UPSTREAM = os.getenv("OPENCODE_URL", "http://127.0.0.1:4096").rstrip("/")
40
+ UPSTREAM_WS = UPSTREAM.replace("http://", "ws://").replace("https://", "wss://")
41
+
42
+ HOME = Path(os.getenv("HOME", "/home/node"))
43
+ ROOTS = {
44
+ "workspace": Path(os.getenv("WORKSPACE_DIR", HOME / "workspace")),
45
+ "sessions": Path(os.getenv("OPENCODE_DATA_DIR", HOME / ".local/share/opencode")) / "storage" / "session",
46
+ "config": Path(os.getenv("OPENCODE_CONFIG_DIR", HOME / ".config/opencode")),
47
+ }
48
+
49
+ SHELL = Path(__file__).with_name("shell.html")
50
+ TEXT_LIMIT = 512 * 1024
51
+ SEARCH_LIMIT = 300
52
+ ZIP_LIMIT = 300 * 1024 * 1024
53
+ UPLOAD_LIMIT = 50 * 1024 * 1024 # 50 MB
54
+
55
+ # Security Settings
56
+ UNLOCK_SECRET = os.getenv("UNLOCK_SECRET") or os.getenv("VAULT_SECRET", "Ghar777").strip()
57
+ ACCESS_PIN = os.getenv("ACCESS_PIN", "").strip()
58
+ HF_READ_TOKEN = os.getenv("HF_READ_TOKEN", "").strip() or os.getenv("HF_TOKEN", "").strip()
59
+ DIRECT_SESSION_TIMEOUT = int(os.getenv("DIRECT_SESSION_TIMEOUT", "600")) # 10 minutes
60
+
61
+ # State tracking
62
+ state = {
63
+ "last_direct_session": 0.0,
64
+ "direct_mode_pause_external": os.getenv("DIRECT_MODE_PAUSE", "1") in {"1", "true", "True"},
65
+ }
66
+
67
+ HOP_HEADERS = {
68
+ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
69
+ "te", "trailer", "trailers", "transfer-encoding", "upgrade", "host",
70
+ "content-length",
71
+ }
72
+ STRIP_HEADERS = {
73
+ "x-frame-options",
74
+ "content-security-policy",
75
+ "content-security-policy-report-only",
76
+ "date",
77
+ }
78
+
79
+ app = FastAPI(title="OpenCode Space Bridge", docs_url=None, redoc_url=None)
80
+
81
+ # Enable CORS for external frontends
82
+ app.add_middleware(
83
+ CORSMiddleware,
84
+ allow_origins=["*"],
85
+ allow_credentials=True,
86
+ allow_methods=["*"],
87
+ allow_headers=["*"],
88
+ )
89
+
90
+ client = httpx.AsyncClient(timeout=None, follow_redirects=False)
91
+
92
+
93
+ def compute_daily_pin(day_str: str) -> str:
94
+ """Computes the 8-digit PIN using HMAC-SHA256 for a given YYYY-MM-DD cycle day."""
95
+ h = hmac.new(UNLOCK_SECRET.encode("utf-8"), day_str.encode("utf-8"), hashlib.sha256).hexdigest()
96
+ return f"{int(h[:8], 16) % 100000000:08d}"
97
+
98
+
99
+ def get_valid_pins() -> set:
100
+ """Returns valid daily PINs.
101
+
102
+ Rollover occurs at 05:30 AM IST (00:00:00 UTC).
103
+ Includes current day and previous day for transition grace.
104
+ """
105
+ now_utc = datetime.now(timezone.utc)
106
+ today_str = now_utc.strftime("%Y-%m-%d")
107
+ yesterday_str = (now_utc - timedelta(days=1)).strftime("%Y-%m-%d")
108
+
109
+ pins = {compute_daily_pin(today_str), compute_daily_pin(yesterday_str)}
110
+ if ACCESS_PIN:
111
+ pins.add(ACCESS_PIN)
112
+ return pins
113
+
114
+
115
+ def is_pin_valid(pin_val: Optional[str]) -> bool:
116
+ if not (UNLOCK_SECRET or ACCESS_PIN):
117
+ return True
118
+ return bool(pin_val and pin_val.strip() in get_valid_pins())
119
+
120
+
121
+ def is_direct_active() -> bool:
122
+ return (time.time() - state["last_direct_session"]) < DIRECT_SESSION_TIMEOUT
123
+
124
+
125
+ def verify_auth(
126
+ x_access_pin: Optional[str] = None,
127
+ authorization: Optional[str] = None,
128
+ pin: Optional[str] = Query(None),
129
+ token: Optional[str] = Query(None),
130
+ cookie_pin: Optional[str] = None,
131
+ ):
132
+ # 1. Verify Hugging Face Read Token authorization if configured
133
+ if HF_READ_TOKEN:
134
+ bearer_token = ""
135
+ if authorization and authorization.lower().startswith("bearer "):
136
+ bearer_token = authorization[7:].strip()
137
+ elif token:
138
+ bearer_token = token.strip()
139
+
140
+ if bearer_token != HF_READ_TOKEN:
141
+ raise HTTPException(status_code=401, detail="Invalid or missing Hugging Face authorization token")
142
+
143
+ # 2. Verify 8-Digit Daily Unlock PIN
144
+ req_pin = (x_access_pin or pin or cookie_pin or "").strip()
145
+ if UNLOCK_SECRET or ACCESS_PIN:
146
+ if not is_pin_valid(req_pin):
147
+ raise HTTPException(status_code=401, detail="Invalid or expired daily 8-digit unlock PIN")
148
+
149
+
150
+ def get_lock_html(error_msg: str = "") -> str:
151
+ err_html = f'<div style="color:#ef4444;font-size:13px;margin-bottom:12px;">{error_msg}</div>' if error_msg else ''
152
+ return f"""<!DOCTYPE html>
153
+ <html lang="en">
154
+ <head>
155
+ <meta charset="UTF-8">
156
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
157
+ <title>OpenCode Access Locked</title>
158
+ <style>
159
+ body {{ background:#0d1117; color:#c9d1d9; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; display:flex; align-items:center; justify-content:center; height:100vh; margin:0; }}
160
+ .card {{ background:#161b22; border:1px solid #30363d; border-radius:12px; padding:32px; width:90%; max-width:360px; text-align:center; box-shadow:0 8px 24px rgba(0,0,0,0.5); }}
161
+ h2 {{ color:#f0f6fc; font-size:18px; margin-top:0; }}
162
+ p {{ color:#8b949e; font-size:13px; margin-bottom:20px; }}
163
+ input {{ width:100%; box-sizing:border-box; background:#0d1117; border:1px solid #30363d; border-radius:8px; color:white; font-size:22px; letter-spacing:4px; text-align:center; padding:10px; margin-bottom:16px; outline:none; }}
164
+ input:focus {{ border-color:#58a6ff; }}
165
+ button {{ width:100%; background:#238636; color:white; border:none; padding:10px; border-radius:8px; font-weight:600; cursor:pointer; font-size:14px; }}
166
+ button:hover {{ background:#2ea043; }}
167
+ </style>
168
+ </head>
169
+ <body>
170
+ <div class="card">
171
+ <div style="font-size:36px;margin-bottom:12px;">🔒</div>
172
+ <h2>OpenCode Access Locked</h2>
173
+ <p>Authentication Required to Access Agent Environment.</p>
174
+ {err_html}
175
+ <form method="GET">
176
+ <input type="password" name="pin" maxlength="8" pattern="[0-9]*" inputmode="numeric" placeholder="••••••••" autofocus required>
177
+ <button type="submit">Unlock Environment</button>
178
+ </form>
179
+ </div>
180
+ </body>
181
+ </html>"""
182
+
183
+
184
+ def _root(root: str) -> Path:
185
+ if root not in ROOTS:
186
+ raise HTTPException(status_code=404, detail=f"unknown root {root!r}")
187
+ return ROOTS[root].resolve()
188
+
189
+
190
+ def _resolve(root: str, rel: str) -> Path:
191
+ base = _root(root)
192
+ rel = rel.lstrip("/")
193
+ target = (base / rel).resolve() if rel else base
194
+ if target != base and base not in target.parents:
195
+ raise HTTPException(status_code=403, detail="path escapes root")
196
+ return target
197
+
198
+
199
+ def _rel(base: Path, target: Path) -> str:
200
+ try:
201
+ rel = target.relative_to(base).as_posix()
202
+ except ValueError:
203
+ return ""
204
+ return "" if rel == "." else rel
205
+
206
+
207
+ def _entry(root: str, base: Path, p: Path) -> dict:
208
+ try:
209
+ st = p.stat()
210
+ except OSError:
211
+ st = None
212
+ is_dir = p.is_dir()
213
+ return {
214
+ "name": p.name,
215
+ "path": _rel(base, p),
216
+ "type": "dir" if is_dir else "file",
217
+ "size": 0 if is_dir or st is None else st.st_size,
218
+ "mtime": 0 if st is None else int(st.st_mtime),
219
+ }
220
+
221
+
222
+ # ---------------- API ENDPOINTS ----------------
223
+
224
+ @app.get("/__health")
225
+ async def health():
226
+ ok = True
227
+ try:
228
+ async with httpx.AsyncClient(timeout=2.0) as c:
229
+ await c.get(UPSTREAM + "/")
230
+ except Exception:
231
+ ok = False
232
+
233
+ now_utc = datetime.now(timezone.utc)
234
+ return {
235
+ "ok": ok,
236
+ "upstream": UPSTREAM,
237
+ "direct_active": is_direct_active(),
238
+ "direct_remaining_seconds": max(0, int(DIRECT_SESSION_TIMEOUT - (time.time() - state["last_direct_session"]))) if is_direct_active() else 0,
239
+ "cycle_date": now_utc.strftime("%Y-%m-%d"),
240
+ "roots": {k: str(v) for k, v in ROOTS.items()}
241
+ }
242
+
243
+
244
+ @app.get("/__api/roots")
245
+ async def api_roots(
246
+ request: Request,
247
+ x_access_pin: Optional[str] = Header(None),
248
+ authorization: Optional[str] = Header(None),
249
+ pin: Optional[str] = Query(None),
250
+ token: Optional[str] = Query(None),
251
+ ):
252
+ cookie_pin = request.cookies.get("opencode_pin")
253
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
254
+ return {"roots": [{"id": k, "path": str(_root(k))} for k in ROOTS]}
255
+
256
+
257
+ @app.get("/__api/tree")
258
+ async def api_tree(
259
+ request: Request,
260
+ root: str = "workspace",
261
+ path: str = "",
262
+ x_access_pin: Optional[str] = Header(None),
263
+ authorization: Optional[str] = Header(None),
264
+ pin: Optional[str] = Query(None),
265
+ token: Optional[str] = Query(None),
266
+ ):
267
+ cookie_pin = request.cookies.get("opencode_pin")
268
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
269
+ base = _root(root)
270
+ target = _resolve(root, path)
271
+ if not target.exists():
272
+ raise HTTPException(status_code=404, detail="not found")
273
+ if target.is_file():
274
+ return {"root": root, "path": _rel(base, target), "entries": []}
275
+
276
+ entries = []
277
+ try:
278
+ children = list(target.iterdir())
279
+ except OSError as exc:
280
+ raise HTTPException(status_code=403, detail=str(exc))
281
+ for child in children:
282
+ if not child.is_symlink() or child.exists():
283
+ entries.append(_entry(root, base, child))
284
+ entries.sort(key=lambda e: (e["type"] != "dir", e["name"].lower()))
285
+ return {"root": root, "path": _rel(base, target), "entries": entries}
286
+
287
+
288
+ @app.get("/__api/file")
289
+ async def api_file(
290
+ request: Request,
291
+ root: str = "workspace",
292
+ path: str = "",
293
+ x_access_pin: Optional[str] = Header(None),
294
+ authorization: Optional[str] = Header(None),
295
+ pin: Optional[str] = Query(None),
296
+ token: Optional[str] = Query(None),
297
+ ):
298
+ cookie_pin = request.cookies.get("opencode_pin")
299
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
300
+ target = _resolve(root, path)
301
+ if not target.is_file():
302
+ raise HTTPException(status_code=404, detail="not a file")
303
+
304
+ size = target.stat().st_size
305
+ with target.open("rb") as fh:
306
+ head = fh.read(4096)
307
+ binary = b"\x00" in head
308
+ payload = {
309
+ "name": target.name,
310
+ "path": _rel(_root(root), target),
311
+ "size": size,
312
+ "binary": binary,
313
+ "truncated": False,
314
+ "content": None,
315
+ }
316
+ if not binary:
317
+ with target.open("rb") as fh:
318
+ raw = fh.read(TEXT_LIMIT + 1)
319
+ payload["truncated"] = len(raw) > TEXT_LIMIT
320
+ payload["content"] = raw[:TEXT_LIMIT].decode("utf-8", errors="replace")
321
+ return payload
322
+
323
+
324
+ @app.get("/__api/raw")
325
+ async def api_raw(
326
+ request: Request,
327
+ root: str = "workspace",
328
+ path: str = "",
329
+ x_access_pin: Optional[str] = Header(None),
330
+ authorization: Optional[str] = Header(None),
331
+ pin: Optional[str] = Query(None),
332
+ token: Optional[str] = Query(None),
333
+ ):
334
+ cookie_pin = request.cookies.get("opencode_pin")
335
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
336
+ target = _resolve(root, path)
337
+ if not target.is_file():
338
+ raise HTTPException(status_code=404, detail="not a file")
339
+ return FileResponse(target, filename=target.name, media_type="application/octet-stream")
340
+
341
+
342
+ @app.get("/__api/zip")
343
+ async def api_zip(
344
+ request: Request,
345
+ root: str = "workspace",
346
+ path: str = "",
347
+ x_access_pin: Optional[str] = Header(None),
348
+ authorization: Optional[str] = Header(None),
349
+ pin: Optional[str] = Query(None),
350
+ token: Optional[str] = Query(None),
351
+ ):
352
+ cookie_pin = request.cookies.get("opencode_pin")
353
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
354
+ target = _resolve(root, path)
355
+ if not target.exists():
356
+ raise HTTPException(status_code=404, detail="not found")
357
+ buf = BytesIO()
358
+ total = 0
359
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
360
+ if target.is_file():
361
+ zf.write(target, target.name)
362
+ name = target.name + ".zip"
363
+ else:
364
+ base = target
365
+ name = (base.name or "root") + ".zip"
366
+ for child in sorted(base.rglob("*")):
367
+ if child.is_file():
368
+ total += child.stat().st_size
369
+ if total > ZIP_LIMIT:
370
+ raise HTTPException(status_code=413, detail="archive too large")
371
+ zf.write(child, child.relative_to(base).as_posix())
372
+ buf.seek(0)
373
+ headers = {"Content-Disposition": f'attachment; filename="{name}"'}
374
+ return StreamingResponse(buf, media_type="application/zip", headers=headers)
375
+
376
+
377
+ @app.get("/__api/search")
378
+ async def api_search(
379
+ request: Request,
380
+ q: str = "",
381
+ root: str = "workspace",
382
+ limit: int = SEARCH_LIMIT,
383
+ x_access_pin: Optional[str] = Header(None),
384
+ authorization: Optional[str] = Header(None),
385
+ pin: Optional[str] = Query(None),
386
+ token: Optional[str] = Query(None),
387
+ ):
388
+ cookie_pin = request.cookies.get("opencode_pin")
389
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
390
+ base = _root(root)
391
+ needle = q.strip().lower()
392
+ if not needle:
393
+ return {"results": []}
394
+ results = []
395
+ for dirpath, dirnames, filenames in os.walk(base):
396
+ dirnames[:] = [d for d in dirnames if d not in {".git", "node_modules", "__pycache__", ".venv"}]
397
+ for name in dirnames + filenames:
398
+ if needle in name.lower():
399
+ p = Path(dirpath) / name
400
+ results.append(_entry(root, base, p))
401
+ if len(results) >= limit:
402
+ return {"results": results, "truncated": True}
403
+ return {"results": results, "truncated": False}
404
+
405
+
406
+ # ---------------- FILE UPLOAD (<50MB) ----------------
407
+
408
+ @app.post("/__api/upload")
409
+ async def api_upload(
410
+ request: Request,
411
+ file: UploadFile = File(...),
412
+ path: str = Query(""),
413
+ root: str = Query("workspace"),
414
+ x_access_pin: Optional[str] = Header(None),
415
+ authorization: Optional[str] = Header(None),
416
+ pin: Optional[str] = Query(None),
417
+ token: Optional[str] = Query(None),
418
+ ):
419
+ cookie_pin = request.cookies.get("opencode_pin")
420
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
421
+ base = _root(root)
422
+ dest_dir = _resolve(root, path)
423
+ if not dest_dir.is_dir():
424
+ dest_dir = dest_dir.parent
425
+
426
+ target_file = (dest_dir / file.filename).resolve()
427
+ if base not in target_file.parents and target_file != base:
428
+ raise HTTPException(status_code=403, detail="path escapes root")
429
+
430
+ bytes_read = 0
431
+ with target_file.open("wb") as buffer:
432
+ while True:
433
+ chunk = await file.read(1024 * 64)
434
+ if not chunk:
435
+ break
436
+ bytes_read += len(chunk)
437
+ if bytes_read > UPLOAD_LIMIT:
438
+ target_file.unlink(missing_ok=True)
439
+ raise HTTPException(status_code=413, detail="File size exceeds 50MB limit")
440
+ buffer.write(chunk)
441
+
442
+ return {
443
+ "ok": True,
444
+ "name": file.filename,
445
+ "path": _rel(base, target_file),
446
+ "size": bytes_read,
447
+ }
448
+
449
+
450
+ # ---------------- SESSIONS LIST & SWITCH (LEFT SIDEBAR) ----------------
451
+
452
+ @app.get("/__api/sessions")
453
+ async def api_sessions(
454
+ request: Request,
455
+ x_access_pin: Optional[str] = Header(None),
456
+ authorization: Optional[str] = Header(None),
457
+ pin: Optional[str] = Query(None),
458
+ token: Optional[str] = Query(None),
459
+ ):
460
+ cookie_pin = request.cookies.get("opencode_pin")
461
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
462
+ sessions_dir = ROOTS["sessions"]
463
+ sessions = []
464
+
465
+ if sessions_dir.exists() and sessions_dir.is_dir():
466
+ for item in sorted(sessions_dir.iterdir(), key=lambda p: p.stat().st_mtime if p.is_file() else 0, reverse=True):
467
+ if item.is_file() and item.suffix == ".json":
468
+ try:
469
+ with item.open("r", encoding="utf-8") as f:
470
+ data = json.load(f)
471
+ title = data.get("title") or data.get("name") or item.stem
472
+ mtime = int(item.stat().st_mtime)
473
+ msg_count = len(data.get("messages", []))
474
+ sessions.append({
475
+ "id": item.stem,
476
+ "title": title,
477
+ "mtime": mtime,
478
+ "messages_count": msg_count,
479
+ })
480
+ except Exception:
481
+ sessions.append({
482
+ "id": item.stem,
483
+ "title": item.stem,
484
+ "mtime": int(item.stat().st_mtime),
485
+ "messages_count": 0,
486
+ })
487
+
488
+ return {"sessions": sessions}
489
+
490
+
491
+ # ---------------- MODEL SWITCHING ----------------
492
+
493
+ @app.get("/__api/models")
494
+ async def api_get_models(
495
+ request: Request,
496
+ x_access_pin: Optional[str] = Header(None),
497
+ authorization: Optional[str] = Header(None),
498
+ pin: Optional[str] = Query(None),
499
+ token: Optional[str] = Query(None),
500
+ ):
501
+ cookie_pin = request.cookies.get("opencode_pin")
502
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
503
+ cfg_file = ROOTS["config"] / "config.json"
504
+ active_model = "default"
505
+ if cfg_file.exists():
506
+ try:
507
+ with cfg_file.open("r", encoding="utf-8") as f:
508
+ cfg = json.load(f)
509
+ active_model = cfg.get("model", "default")
510
+ except Exception:
511
+ pass
512
+
513
+ return {
514
+ "active_model": active_model,
515
+ "available_models": [
516
+ {"id": "claude-3-5-sonnet", "name": "Claude 3.5 Sonnet"},
517
+ {"id": "gpt-4o", "name": "GPT-4o"},
518
+ {"id": "deepseek-coder", "name": "DeepSeek Coder"},
519
+ {"id": "qwen-2.5-coder", "name": "Qwen 2.5 Coder"},
520
+ {"id": "gemini-1.5-pro", "name": "Gemini 1.5 Pro"},
521
+ ]
522
+ }
523
+
524
+
525
+ @app.post("/__api/models")
526
+ async def api_set_model(
527
+ request: Request,
528
+ model_data: dict,
529
+ x_access_pin: Optional[str] = Header(None),
530
+ authorization: Optional[str] = Header(None),
531
+ pin: Optional[str] = Query(None),
532
+ token: Optional[str] = Query(None),
533
+ ):
534
+ cookie_pin = request.cookies.get("opencode_pin")
535
+ verify_auth(x_access_pin, authorization, pin, token, cookie_pin)
536
+ new_model = model_data.get("model", "").strip()
537
+ if not new_model:
538
+ raise HTTPException(status_code=400, detail="model name required")
539
+
540
+ ROOTS["config"].mkdir(parents=True, exist_ok=True)
541
+ cfg_file = ROOTS["config"] / "config.json"
542
+ cfg = {}
543
+ if cfg_file.exists():
544
+ try:
545
+ with cfg_file.open("r", encoding="utf-8") as f:
546
+ cfg = json.load(f)
547
+ except Exception:
548
+ cfg = {}
549
+
550
+ cfg["model"] = new_model
551
+ with cfg_file.open("w", encoding="utf-8") as f:
552
+ json.dump(cfg, f, indent=2)
553
+
554
+ return {"ok": True, "active_model": new_model}
555
+
556
+
557
+ # ---------------- PROXY & REVERSE ROUTING ----------------
558
+
559
+ def _proxy_headers(request: Request) -> dict:
560
+ return {k: v for k, v in request.headers.items() if k.lower() not in HOP_HEADERS}
561
+
562
+
563
+ def _response_headers(upstream: httpx.Response) -> dict:
564
+ return {
565
+ k: v
566
+ for k, v in upstream.headers.items()
567
+ if k.lower() not in HOP_HEADERS and k.lower() not in STRIP_HEADERS
568
+ }
569
+
570
+
571
+ @app.api_route(
572
+ "/{path:path}",
573
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
574
+ )
575
+ async def proxy(path: str, request: Request):
576
+ # Determine PIN from request
577
+ cookie_pin = request.cookies.get("opencode_pin")
578
+ query_pin = request.query_params.get("pin")
579
+ header_pin = request.headers.get("X-Access-Pin")
580
+ effective_pin = query_pin or header_pin or cookie_pin
581
+
582
+ is_navigation = (
583
+ request.method == "GET"
584
+ and path == ""
585
+ and "iframe" not in request.query_params
586
+ and "text/html" in request.headers.get("accept", "")
587
+ )
588
+
589
+ # If visiting root navigation directly in browser
590
+ if is_navigation:
591
+ # Check authentication
592
+ if (UNLOCK_SECRET or ACCESS_PIN) and not is_pin_valid(effective_pin):
593
+ err = "Invalid PIN entered" if query_pin else ""
594
+ return HTMLResponse(get_lock_html(err), status_code=401 if query_pin else 200)
595
+
596
+ # Successfully unlocked direct navigation session
597
+ state["last_direct_session"] = time.time()
598
+ resp = FileResponse(SHELL, media_type="text/html")
599
+ if effective_pin:
600
+ resp.set_cookie("opencode_pin", effective_pin, max_age=86400, httponly=True, samesite="lax")
601
+ return resp
602
+
603
+ # Check origin for external API calls
604
+ origin = request.headers.get("origin") or request.headers.get("referer") or ""
605
+ is_external = "hf.space" not in origin and origin != ""
606
+
607
+ if is_external and state["direct_mode_pause_external"] and is_direct_active():
608
+ return JSONResponse(
609
+ {
610
+ "paused": True,
611
+ "reason": "Direct session active on Hugging Face Space. External API serving temporarily paused to preserve CPU.",
612
+ "remaining_seconds": max(0, int(DIRECT_SESSION_TIMEOUT - (time.time() - state["last_direct_session"])))
613
+ },
614
+ status_code=503,
615
+ )
616
+
617
+ # General auth verification for proxy endpoints
618
+ if UNLOCK_SECRET or ACCESS_PIN or HF_READ_TOKEN:
619
+ auth = request.headers.get("Authorization") or request.query_params.get("token")
620
+ try:
621
+ verify_auth(x_access_pin=effective_pin, authorization=auth, pin=effective_pin, token=auth, cookie_pin=cookie_pin)
622
+ except HTTPException as exc:
623
+ return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
624
+
625
+ params = [(k, v) for k, v in request.query_params.multi_items() if k not in {"iframe", "pin", "token"}]
626
+ url = httpx.URL(f"{UPSTREAM}/{path}", params=params) if params else f"{UPSTREAM}/{path}"
627
+
628
+ try:
629
+ upstream_request = client.build_request(
630
+ request.method,
631
+ url,
632
+ headers=_proxy_headers(request),
633
+ content=request.stream(),
634
+ )
635
+ upstream = await client.send(upstream_request, stream=True)
636
+ except httpx.HTTPError as exc:
637
+ return JSONResponse(
638
+ {"error": "opencode upstream unreachable", "detail": str(exc)},
639
+ status_code=502,
640
+ )
641
+
642
+ return StreamingResponse(
643
+ upstream.aiter_raw(),
644
+ status_code=upstream.status_code,
645
+ headers=_response_headers(upstream),
646
+ background=BackgroundTask(upstream.aclose),
647
+ )
648
+
649
+
650
+ @app.websocket("/{path:path}")
651
+ async def ws_proxy(websocket: WebSocket, path: str):
652
+ if websockets is None:
653
+ await websocket.close(code=1011)
654
+ return
655
+
656
+ # Check PIN from query params or cookies if dynamic unlock PIN configured
657
+ effective_pin = websocket.query_params.get("pin") or websocket.cookies.get("opencode_pin")
658
+ if (UNLOCK_SECRET or ACCESS_PIN) and not is_pin_valid(effective_pin):
659
+ await websocket.close(code=4401)
660
+ return
661
+
662
+ protocol = websocket.headers.get("sec-websocket-protocol")
663
+ await websocket.accept(subprotocol=protocol)
664
+
665
+ query = "&".join(f"{k}={v}" for k, v in websocket.query_params.items() if k not in {"pin", "token"})
666
+ target = f"{UPSTREAM_WS}/{path}" + (f"?{query}" if query else "")
667
+ subprotocols = [p.strip() for p in protocol.split(",")] if protocol else None
668
+
669
+ try:
670
+ async with websockets.connect(target, subprotocols=subprotocols, max_size=None) as upstream:
671
+
672
+ async def pump_upstream():
673
+ try:
674
+ async for message in upstream:
675
+ if isinstance(message, bytes):
676
+ await websocket.send_bytes(message)
677
+ else:
678
+ await websocket.send_text(message)
679
+ except Exception:
680
+ pass
681
+
682
+ task = asyncio.create_task(pump_upstream())
683
+ try:
684
+ while True:
685
+ message = await websocket.receive()
686
+ if message["type"] == "websocket.disconnect":
687
+ break
688
+ if message.get("bytes") is not None:
689
+ await upstream.send(message["bytes"])
690
+ elif message.get("text") is not None:
691
+ await upstream.send(message["text"])
692
+ except WebSocketDisconnect:
693
+ pass
694
+ finally:
695
+ task.cancel()
696
+ except Exception:
697
+ try:
698
+ await websocket.close()
699
+ except Exception:
700
+ pass
requirements.txt CHANGED
@@ -1,3 +1,7 @@
1
- fastapi
2
- uvicorn
3
- python-multipart
 
 
 
 
 
1
+ fastapi>=0.100.0
2
+ uvicorn[standard]>=0.23.0
3
+ httpx>=0.24.0
4
+ websockets>=11.0
5
+ huggingface_hub>=0.20.0
6
+ python-multipart>=0.0.6
7
+ aiofiles>=23.2.0
shell.html ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>opencode</title>
7
+ <style>
8
+ :root {
9
+ --bg: #0b0d10;
10
+ --bg-alt: #11151a;
11
+ --bg-hover: #1a2028;
12
+ --border: #232b35;
13
+ --text: #d7dde5;
14
+ --muted: #7d8794;
15
+ --accent: #63b3ed;
16
+ --accent-dim: #2b6cb0;
17
+ --danger: #f56565;
18
+ --radius: 6px;
19
+ --sidebar: 300px;
20
+ }
21
+ * { box-sizing: border-box; }
22
+ html, body { height: 100%; margin: 0; }
23
+ body {
24
+ background: var(--bg);
25
+ color: var(--text);
26
+ font: 13px/1.45 ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
27
+ overflow: hidden;
28
+ }
29
+ #app { display: flex; height: 100%; }
30
+
31
+ /* ---------- sidebar ---------- */
32
+ #sidebar {
33
+ width: var(--sidebar);
34
+ min-width: 200px;
35
+ max-width: 70vw;
36
+ display: flex;
37
+ flex-direction: column;
38
+ background: var(--bg-alt);
39
+ border-right: 1px solid var(--border);
40
+ }
41
+ #sidebar.collapsed { display: none; }
42
+
43
+ .bar {
44
+ display: flex;
45
+ align-items: center;
46
+ gap: 6px;
47
+ padding: 8px;
48
+ border-bottom: 1px solid var(--border);
49
+ }
50
+ .bar .title {
51
+ font-weight: 600;
52
+ letter-spacing: .04em;
53
+ text-transform: uppercase;
54
+ font-size: 10px;
55
+ color: var(--muted);
56
+ flex: 1;
57
+ overflow: hidden;
58
+ text-overflow: ellipsis;
59
+ white-space: nowrap;
60
+ }
61
+ button, select, input {
62
+ font: inherit;
63
+ color: var(--text);
64
+ background: var(--bg);
65
+ border: 1px solid var(--border);
66
+ border-radius: var(--radius);
67
+ padding: 4px 8px;
68
+ outline: none;
69
+ }
70
+ button { cursor: pointer; }
71
+ button:hover { background: var(--bg-hover); border-color: var(--accent-dim); }
72
+ button.icon { padding: 4px 7px; line-height: 1; }
73
+ select { padding: 4px 6px; }
74
+ input:focus, select:focus { border-color: var(--accent-dim); }
75
+
76
+ .search { padding: 8px; border-bottom: 1px solid var(--border); }
77
+ .search input { width: 100%; }
78
+
79
+ #tree { flex: 1; overflow: auto; padding: 4px 0 24px; }
80
+ .node { user-select: none; }
81
+ .row {
82
+ display: flex;
83
+ align-items: center;
84
+ gap: 5px;
85
+ padding: 3px 8px 3px 0;
86
+ white-space: nowrap;
87
+ cursor: pointer;
88
+ border-left: 2px solid transparent;
89
+ }
90
+ .row:hover { background: var(--bg-hover); }
91
+ .row.active { background: var(--bg-hover); border-left-color: var(--accent); }
92
+ .row .caret {
93
+ width: 12px;
94
+ color: var(--muted);
95
+ flex: none;
96
+ text-align: center;
97
+ transition: transform .12s;
98
+ }
99
+ .row .caret.open { transform: rotate(90deg); }
100
+ .row .ico { flex: none; width: 14px; text-align: center; color: var(--muted); }
101
+ .row .ico.dir { color: var(--accent); }
102
+ .row .name { overflow: hidden; text-overflow: ellipsis; }
103
+ .row .name.dir { color: var(--text); font-weight: 600; }
104
+ .row .size { margin-left: auto; color: var(--muted); font-size: 10px; padding-left: 8px; }
105
+ .children { display: none; }
106
+ .children.open { display: block; }
107
+
108
+ .empty, .hint { padding: 10px; color: var(--muted); font-size: 11px; }
109
+ .status {
110
+ border-top: 1px solid var(--border);
111
+ padding: 6px 10px;
112
+ font-size: 10px;
113
+ color: var(--muted);
114
+ display: flex;
115
+ justify-content: space-between;
116
+ }
117
+
118
+ /* ---------- resizer ---------- */
119
+ #resizer {
120
+ width: 4px;
121
+ cursor: col-resize;
122
+ background: transparent;
123
+ flex: none;
124
+ }
125
+ #resizer:hover { background: var(--accent-dim); }
126
+
127
+ /* ---------- main ---------- */
128
+ #main { flex: 1; position: relative; min-width: 0; }
129
+ #frame { width: 100%; height: 100%; border: 0; background: var(--bg); display: block; }
130
+ #float {
131
+ position: absolute; top: 8px; right: 12px; z-index: 5;
132
+ display: flex; gap: 6px; opacity: .25; transition: opacity .15s;
133
+ }
134
+ #float:hover { opacity: 1; }
135
+ #float a, #float button {
136
+ background: rgba(17,21,26,.9);
137
+ border: 1px solid var(--border);
138
+ color: var(--muted);
139
+ text-decoration: none;
140
+ padding: 3px 8px;
141
+ border-radius: var(--radius);
142
+ font-size: 11px;
143
+ }
144
+
145
+ /* ---------- modal ---------- */
146
+ #modal {
147
+ position: fixed; inset: 0; z-index: 50;
148
+ background: rgba(0,0,0,.6);
149
+ display: none;
150
+ padding: 4vh 4vw;
151
+ }
152
+ #modal.open { display: flex; }
153
+ #modal .panel {
154
+ margin: auto;
155
+ width: min(1100px, 100%);
156
+ height: 100%;
157
+ display: flex;
158
+ flex-direction: column;
159
+ background: var(--bg-alt);
160
+ border: 1px solid var(--border);
161
+ border-radius: 10px;
162
+ overflow: hidden;
163
+ box-shadow: 0 20px 60px rgba(0,0,0,.6);
164
+ }
165
+ #modal .head {
166
+ display: flex; align-items: center; gap: 8px;
167
+ padding: 8px 10px; border-bottom: 1px solid var(--border);
168
+ }
169
+ #modal .head .fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
170
+ #modal .head .meta { color: var(--muted); font-size: 10px; }
171
+ #modal pre {
172
+ flex: 1; margin: 0; padding: 12px 14px;
173
+ overflow: auto;
174
+ font-size: 12px; line-height: 1.5;
175
+ tab-size: 2;
176
+ white-space: pre;
177
+ }
178
+ #modal .foot { color: var(--muted); font-size: 10px; padding: 6px 12px; border-top: 1px solid var(--border); }
179
+ a.btn {
180
+ text-decoration: none; color: var(--text);
181
+ border: 1px solid var(--border); border-radius: var(--radius);
182
+ padding: 3px 8px; font-size: 11px; background: var(--bg);
183
+ }
184
+ a.btn:hover { background: var(--bg-hover); border-color: var(--accent-dim); }
185
+
186
+ @media (max-width: 720px) {
187
+ #sidebar { width: 80vw; position: absolute; z-index: 20; height: 100%; }
188
+ #resizer { display: none; }
189
+ }
190
+ </style>
191
+ </head>
192
+ <body>
193
+ <div id="app">
194
+ <aside id="sidebar">
195
+ <div class="bar">
196
+ <span class="title" id="rootLabel">workspace</span>
197
+ <select id="rootSelect" title="Storage root"></select>
198
+ <button class="icon" id="refreshBtn" title="Refresh">&#x27F3;</button>
199
+ <button class="icon" id="collapseBtn" title="Hide sidebar">&laquo;</button>
200
+ </div>
201
+ <div class="search"><input id="searchInput" placeholder="filter / search files…" /></div>
202
+ <div id="tree"><div class="hint">loading…</div></div>
203
+ <div class="status"><span id="statLeft">—</span><span id="statRight"></span></div>
204
+ </aside>
205
+ <div id="resizer"></div>
206
+ <main id="main">
207
+ <iframe id="frame" src="/?iframe=1" title="opencode"></iframe>
208
+ <div id="float">
209
+ <button id="showSidebar" title="Show file explorer" style="display:none">&raquo;</button>
210
+ <a id="pop" href="/?iframe=1" target="_blank" title="Open chat in new tab">&nearr;</a>
211
+ </div>
212
+ </main>
213
+ </div>
214
+
215
+ <div id="modal">
216
+ <div class="panel">
217
+ <div class="head">
218
+ <span class="fname" id="mName"></span>
219
+ <span class="meta" id="mMeta"></span>
220
+ <a class="btn" id="mRaw" target="_blank">raw</a>
221
+ <a class="btn" id="mZip" target="_blank">zip</a>
222
+ <button class="icon" id="mClose">&times;</button>
223
+ </div>
224
+ <pre id="mBody"></pre>
225
+ <div class="foot" id="mFoot"></div>
226
+ </div>
227
+ </div>
228
+
229
+ <script>
230
+ (() => {
231
+ const $ = (id) => document.getElementById(id);
232
+ const treeEl = $('tree');
233
+ const state = { root: 'workspace', open: new Set(), active: null, search: '' };
234
+
235
+ const fmtSize = (n) => {
236
+ if (!n) return '';
237
+ const u = ['B', 'K', 'M', 'G', 'T'];
238
+ let i = 0;
239
+ while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
240
+ return (i === 0 ? n : n.toFixed(1)) + u[i];
241
+ };
242
+ const enc = encodeURIComponent;
243
+
244
+ async function api(url) {
245
+ const r = await fetch(url, { headers: { accept: 'application/json' } });
246
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || r.statusText);
247
+ return r.json();
248
+ }
249
+
250
+ function rowFor(entry, depth) {
251
+ const node = document.createElement('div');
252
+ node.className = 'node';
253
+
254
+ const row = document.createElement('div');
255
+ row.className = 'row' + (state.active === state.root + ':' + entry.path ? ' active' : '');
256
+ row.style.paddingLeft = (depth * 14 + 6) + 'px';
257
+ row.dataset.path = entry.path;
258
+ row.dataset.type = entry.type;
259
+
260
+ const caret = document.createElement('span');
261
+ caret.className = 'caret';
262
+ caret.textContent = entry.type === 'dir' ? '\u25B8' : '';
263
+
264
+ const ico = document.createElement('span');
265
+ ico.className = 'ico' + (entry.type === 'dir' ? ' dir' : '');
266
+ ico.textContent = entry.type === 'dir' ? '\u25A0' : '\u2022';
267
+
268
+ const name = document.createElement('span');
269
+ name.className = 'name' + (entry.type === 'dir' ? ' dir' : '');
270
+ name.textContent = entry.name;
271
+
272
+ const size = document.createElement('span');
273
+ size.className = 'size';
274
+ size.textContent = entry.type === 'dir' ? '' : fmtSize(entry.size);
275
+
276
+ row.append(caret, ico, name, size);
277
+ node.append(row);
278
+
279
+ let childBox = null;
280
+ const key = state.root + ':' + entry.path;
281
+
282
+ async function toggle() {
283
+ if (entry.type !== 'dir') { preview(entry); return; }
284
+ if (!childBox) {
285
+ childBox = document.createElement('div');
286
+ childBox.className = 'children';
287
+ childBox.style.paddingLeft = '0px';
288
+ node.append(childBox);
289
+ try {
290
+ const data = await api(`/__api/tree?root=${enc(state.root)}&path=${enc(entry.path)}`);
291
+ if (!data.entries.length) {
292
+ childBox.innerHTML = '<div class="empty">empty</div>';
293
+ } else {
294
+ for (const child of data.entries) childBox.append(rowFor(child, depth + 1));
295
+ }
296
+ } catch (e) {
297
+ childBox.innerHTML = `<div class="empty">${e.message}</div>`;
298
+ }
299
+ }
300
+ const isOpen = childBox.classList.toggle('open');
301
+ caret.classList.toggle('open', isOpen);
302
+ if (isOpen) state.open.add(key); else state.open.delete(key);
303
+ }
304
+
305
+ row.addEventListener('click', () => { setActive(key); toggle(); });
306
+ return node;
307
+ }
308
+
309
+ function setActive(key) {
310
+ state.active = key;
311
+ document.querySelectorAll('.row.active').forEach((el) => el.classList.remove('active'));
312
+ const [root, ...rest] = key.split(':');
313
+ const path = rest.join(':');
314
+ const sel = `.row[data-path="${CSS.escape(path)}"]`;
315
+ document.querySelectorAll(sel).forEach((el) => el.classList.add('active'));
316
+ }
317
+
318
+ async function loadRoot() {
319
+ treeEl.innerHTML = '<div class="hint">loading…</div>';
320
+ state.open.clear();
321
+ try {
322
+ const data = await api(`/__api/tree?root=${enc(state.root)}&path=`);
323
+ treeEl.innerHTML = '';
324
+ if (!data.entries.length) treeEl.innerHTML = '<div class="empty">no files yet — ask the agent to create some</div>';
325
+ for (const e of data.entries) treeEl.append(rowFor(e, 0));
326
+ } catch (e) {
327
+ treeEl.innerHTML = `<div class="empty">${e.message}</div>`;
328
+ }
329
+ loadStats();
330
+ }
331
+
332
+ async function loadStats() {
333
+ try {
334
+ const s = await api(`/__api/stats?root=${enc(state.root)}`);
335
+ $('statLeft').textContent = `${s.files} files`;
336
+ $('statRight').textContent = fmtSize(s.bytes);
337
+ $('rootLabel').textContent = state.root;
338
+ } catch (_) { /* ignore */ }
339
+ }
340
+
341
+ let searchTimer = null;
342
+ $('searchInput').addEventListener('input', (ev) => {
343
+ const q = ev.target.value.trim();
344
+ clearTimeout(searchTimer);
345
+ if (!q) { loadRoot(); return; }
346
+ searchTimer = setTimeout(async () => {
347
+ treeEl.innerHTML = '<div class="hint">searching…</div>';
348
+ try {
349
+ const data = await api(`/__api/search?root=${enc(state.root)}&q=${enc(q)}`);
350
+ treeEl.innerHTML = '';
351
+ if (!data.results.length) treeEl.innerHTML = '<div class="empty">no matches</div>';
352
+ for (const e of data.results) {
353
+ const row = rowFor(e, 0);
354
+ treeEl.append(row);
355
+ }
356
+ if (data.truncated) treeEl.insertAdjacentHTML('beforeend', '<div class="hint">results truncated…</div>');
357
+ } catch (e) {
358
+ treeEl.innerHTML = `<div class="empty">${e.message}</div>`;
359
+ }
360
+ }, 250);
361
+ });
362
+
363
+ async function preview(entry) {
364
+ $('modal').classList.add('open');
365
+ $('mName').textContent = entry.path || entry.name;
366
+ $('mMeta').textContent = fmtSize(entry.size);
367
+ $('mBody').textContent = 'loading…';
368
+ $('mFoot').textContent = '';
369
+ const qs = `root=${enc(state.root)}&path=${enc(entry.path)}`;
370
+ $('mRaw').href = `/__api/raw?${qs}`;
371
+ $('mZip').href = `/__api/zip?${qs}`;
372
+ try {
373
+ const data = await api(`/__api/file?${qs}`);
374
+ if (data.binary) {
375
+ $('mBody').textContent = '(binary file — use raw/zip to download)';
376
+ } else {
377
+ $('mBody').textContent = data.content ?? '';
378
+ }
379
+ $('mMeta').textContent = fmtSize(data.size);
380
+ $('mFoot').textContent = data.truncated ? `truncated at ${fmtSize(512 * 1024)} — use raw for full file` : '';
381
+ } catch (e) {
382
+ $('mBody').textContent = e.message;
383
+ }
384
+ }
385
+
386
+ $('mClose').addEventListener('click', () => $('modal').classList.remove('open'));
387
+ $('modal').addEventListener('click', (e) => { if (e.target.id === 'modal') $('modal').classList.remove('open'); });
388
+ document.addEventListener('keydown', (e) => {
389
+ if (e.key === 'Escape') $('modal').classList.remove('open');
390
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'b') {
391
+ e.preventDefault();
392
+ toggleSidebar();
393
+ }
394
+ });
395
+
396
+ $('refreshBtn').addEventListener('click', loadRoot);
397
+ $('rootSelect').addEventListener('change', (e) => { state.root = e.target.value; state.active = null; $('searchInput').value = ''; loadRoot(); });
398
+
399
+ function toggleSidebar(force) {
400
+ const sb = $('sidebar');
401
+ const hidden = force !== undefined ? !force : !sb.classList.contains('collapsed');
402
+ sb.classList.toggle('collapsed', hidden);
403
+ $('resizer').style.display = hidden ? 'none' : '';
404
+ $('showSidebar').style.display = hidden ? '' : 'none';
405
+ }
406
+ $('collapseBtn').addEventListener('click', () => toggleSidebar(false));
407
+ $('showSidebar').addEventListener('click', () => toggleSidebar(true));
408
+
409
+ // drag to resize
410
+ (() => {
411
+ const resizer = $('resizer');
412
+ let dragging = false;
413
+ resizer.addEventListener('mousedown', () => { dragging = true; document.body.style.cursor = 'col-resize'; });
414
+ window.addEventListener('mousemove', (e) => {
415
+ if (!dragging) return;
416
+ const w = Math.max(200, Math.min(e.clientX, window.innerWidth * 0.7));
417
+ document.documentElement.style.setProperty('--sidebar', w + 'px');
418
+ });
419
+ window.addEventListener('mouseup', () => { dragging = false; document.body.style.cursor = ''; });
420
+ })();
421
+
422
+ api('/__api/roots').then((d) => {
423
+ const sel = $('rootSelect');
424
+ sel.innerHTML = d.roots.map((r) => `<option value="${r.id}">${r.id}</option>`).join('');
425
+ }).catch(() => {});
426
+
427
+ setInterval(() => { if (!state.search) loadStats(); }, 15000);
428
+ setInterval(() => {
429
+ const openDirs = [];
430
+ document.querySelectorAll('.children.open').forEach((el) => openDirs.push(el));
431
+ if (openDirs.length) refreshOpen();
432
+ }, 10000);
433
+
434
+ async function refreshOpen() {
435
+ const nodes = document.querySelectorAll('.children.open');
436
+ for (const box of nodes) {
437
+ const row = box.previousElementSibling;
438
+ if (!row) continue;
439
+ const path = row.dataset.path;
440
+ if (path === undefined) continue;
441
+ try {
442
+ const data = await api(`/__api/tree?root=${enc(state.root)}&path=${enc(path)}`);
443
+ const depth = parseInt(row.style.paddingLeft || '0', 10) / 14;
444
+ box.innerHTML = '';
445
+ if (!data.entries.length) box.innerHTML = '<div class="empty">empty</div>';
446
+ for (const child of data.entries) box.append(rowFor(child, Math.round(depth)));
447
+ } catch (_) { /* ignore */ }
448
+ }
449
+ }
450
+
451
+ loadRoot();
452
+ })();
453
+ </script>
454
+ </body>
455
+ </html>
start.sh CHANGED
@@ -1,7 +1,32 @@
1
  #!/bin/bash
 
2
 
3
- # Launch the sync agent in the background
 
 
 
 
 
4
  python3 /home/node/sync.py &
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # Start the primary web server
7
- opencode web --port 4096 --hostname 0.0.0.0
 
 
1
  #!/bin/bash
2
+ set -uo pipefail
3
 
4
+ cd /home/node || exit 1
5
+
6
+ echo "[start] hydrating from bucket"
7
+ python3 /home/node/sync.py --pull || echo "[start] pull failed - starting with local files"
8
+
9
+ echo "[start] launching sync daemon"
10
  python3 /home/node/sync.py &
11
+ SYNC_PID=$!
12
+
13
+ cleanup() {
14
+ echo "[start] shutting down"
15
+ kill -TERM "$SYNC_PID" 2>/dev/null
16
+ wait "$SYNC_PID" 2>/dev/null
17
+ kill "${OC_PID:-}" "${WEB_PID:-}" 2>/dev/null
18
+ exit 0
19
+ }
20
+ trap cleanup TERM INT
21
+
22
+ echo "[start] launching opencode (loopback only)"
23
+ opencode web --port 4096 --hostname 127.0.0.1 &
24
+ OC_PID=$!
25
+
26
+ echo "[start] launching shell on :7860"
27
+ uvicorn app:app --host 0.0.0.0 --port 7860 --proxy-headers --no-server-header &
28
+ WEB_PID=$!
29
 
30
+ wait -n "$OC_PID" "$WEB_PID"
31
+ echo "[start] a service exited - shutting down"
32
+ cleanup
sync.py CHANGED
@@ -1,116 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
 
2
  import time
3
- import shutil
4
  from pathlib import Path
5
- from huggingface_hub import HfApi, snapshot_download
6
 
7
- # Configuration fetched from Space Secrets
8
- REPO_ID = os.getenv("DATASET_REPO_ID")
9
- TOKEN = os.getenv("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Core directories
12
- WORKSPACE_DIR = Path("/home/node/workspace")
13
- OPENCODE_DIR = Path("/home/node/.local/share/opencode") # Default Linux storage
14
- GLOBAL_CONFIG_DIR = Path("/home/node/.config/opencode") # Global AGENTS.md + skills
15
- CACHE_DIR = Path("/home/node/.sync_cache")
16
- INTERVAL = 30 * 60 # 30 minutes in seconds
17
 
18
  api = HfApi(token=TOKEN)
 
 
19
 
20
- def initial_pull():
21
- if not REPO_ID:
22
- print("No DATASET_REPO_ID provided. Skipping pull.")
 
 
 
 
 
 
 
 
23
  return
24
-
25
- print("Fetching dataset on startup...")
26
  try:
27
- # Download the latest snapshot of the private dataset
28
- local_dir = snapshot_download(repo_id=REPO_ID, repo_type="dataset", token=TOKEN)
29
-
30
- # Restore workspace files (includes env.example / env.json.local)
31
- ds_workspace = Path(local_dir) / "workspace"
32
- if ds_workspace.exists():
33
- shutil.copytree(ds_workspace, WORKSPACE_DIR, dirs_exist_ok=True)
34
-
35
- # Restore OpenCode sessions and history
36
- ds_opencode = Path(local_dir) / "opencode"
37
- if ds_opencode.exists():
38
- shutil.copytree(ds_opencode, OPENCODE_DIR, dirs_exist_ok=True)
39
-
40
- # Restore global config (AGENTS.md and skills)
41
- ds_global = Path(local_dir) / "global"
42
- if ds_global.exists():
43
- shutil.copytree(ds_global, GLOBAL_CONFIG_DIR, dirs_exist_ok=True)
44
-
45
- # Create an initial cache to track future deletions
46
- shutil.copytree(OPENCODE_DIR, CACHE_DIR, dirs_exist_ok=True)
47
- print("Restoration complete.")
48
- except Exception as e:
49
- print(f"Initial pull failed (likely an empty/new dataset): {e}")
50
-
51
- def push_to_dataset():
52
- if not REPO_ID:
53
  return
54
-
55
- print("Initiating 30-minute sync cycle...")
56
- session_dir = OPENCODE_DIR / "storage" / "session"
57
- cache_session_dir = CACHE_DIR / "storage" / "session"
58
-
59
- # 1. Check for trashed sessions
60
- if cache_session_dir.exists():
61
- for cache_file in cache_session_dir.rglob("*.json"):
62
- relative_path = cache_file.relative_to(cache_session_dir)
63
- current_file = session_dir / relative_path
64
-
65
- if not current_file.exists():
66
- print(f"Detected deleted session: {relative_path}. Moving to trash...")
67
- api.upload_file(
68
- path_or_fileobj=str(cache_file),
69
- path_in_repo=f"trashed/sessions/{relative_path}",
70
- repo_id=REPO_ID,
71
- repo_type="dataset",
72
- token=TOKEN
73
- )
74
-
75
- # 2. Sync workspace and configuration
76
- # The API automatically ignores the push if files are unchanged/empty.
77
- # Files like env.json.local will upload securely since the dataset is private.
78
- api.upload_folder(
79
- folder_path=str(WORKSPACE_DIR),
80
- path_in_repo="workspace",
81
- repo_id=REPO_ID,
82
- repo_type="dataset",
83
- token=TOKEN,
84
- ignore_patterns=["**/__pycache__/*", "**/.git/*"]
85
- )
86
-
87
- api.upload_folder(
88
- folder_path=str(OPENCODE_DIR),
89
- path_in_repo="opencode",
90
- repo_id=REPO_ID,
91
- repo_type="dataset",
92
- token=TOKEN,
93
- ignore_patterns=["**/*.log", "log", "log/**", "**/log/*"]
94
- )
95
-
96
- # 3. Sync global config (AGENTS.md and skills)
97
- api.upload_folder(
98
- folder_path=str(GLOBAL_CONFIG_DIR),
99
- path_in_repo="global",
100
- repo_id=REPO_ID,
101
- repo_type="dataset",
102
- token=TOKEN,
103
- ignore_patterns=["**/node_modules/**", "node_modules/**", "node_modules", "**/*.log"]
104
- )
105
-
106
- # 4. Rebuild local deletion cache
107
- if CACHE_DIR.exists():
108
- shutil.rmtree(CACHE_DIR)
109
- shutil.copytree(OPENCODE_DIR, CACHE_DIR, dirs_exist_ok=True)
110
- print("Sync cycle finished successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  if __name__ == "__main__":
113
- initial_pull()
114
- while True:
115
- time.sleep(INTERVAL)
116
- push_to_dataset()
 
1
+ """Persist the whole Space to a Hugging Face **Storage Bucket**.
2
+
3
+ The bucket is the single source of truth:
4
+
5
+ <bucket>/workspace/... -> /home/node/workspace
6
+ <bucket>/opencode/... -> /home/node/.local/share/opencode
7
+ <bucket>/global/... -> /home/node/.config/opencode
8
+
9
+ Flow
10
+ ----
11
+ * boot : bucket -> container (``python3 sync.py --pull``, run before the web server)
12
+ * every N s : container -> bucket (incremental, deletions propagated)
13
+ * SIGTERM : one last push so a restart/rebuild keeps everything
14
+
15
+ Env
16
+ ---
17
+ BUCKET_REPO_ID namespace/bucket-name (required)
18
+ HF_TOKEN token with write access
19
+ SYNC_INTERVAL_SECONDS default 60
20
+ CREATE_BUCKET "0" to disable auto-creation (default: created private)
21
+ WORKSPACE_DIR default /home/node/workspace
22
+ OPENCODE_DATA_DIR default /home/node/.local/share/opencode
23
+ OPENCODE_CONFIG_DIR default /home/node/.config/opencode
24
+ """
25
+
26
+ import argparse
27
  import os
28
+ import signal
29
+ import sys
30
+ import threading
31
  import time
 
32
  from pathlib import Path
 
33
 
34
+ from huggingface_hub import HfApi
35
+
36
+ HOME = Path(os.getenv("HOME", "/home/node"))
37
+ WORKSPACE = Path(os.getenv("WORKSPACE_DIR", HOME / "workspace"))
38
+ OPENCODE_DATA = Path(os.getenv("OPENCODE_DATA_DIR", HOME / ".local/share/opencode"))
39
+ GLOBAL_CONFIG = Path(os.getenv("OPENCODE_CONFIG_DIR", HOME / ".config/opencode"))
40
+
41
+ BUCKET_ID = os.getenv("BUCKET_REPO_ID", "").strip()
42
+ TOKEN = os.getenv("HF_TOKEN") or None
43
+ INTERVAL = int(os.getenv("SYNC_INTERVAL_SECONDS", "60"))
44
+ CREATE_BUCKET = os.getenv("CREATE_BUCKET", "1") not in {"0", "false", "False", ""}
45
+
46
+ COMMON_IGNORE = ["**/.git/**", ".git/**", "**/__pycache__/**", "**/*.pyc"]
47
 
48
+ TREES = [
49
+ ("workspace", WORKSPACE, COMMON_IGNORE + ["**/node_modules/**", "node_modules/**"]),
50
+ ("opencode", OPENCODE_DATA, ["**/log/**", "log/**", "**/*.log", "**/__pycache__/**"]),
51
+ ("global", GLOBAL_CONFIG, COMMON_IGNORE + ["**/node_modules/**", "node_modules/**"]),
52
+ ]
 
53
 
54
  api = HfApi(token=TOKEN)
55
+ _lock = threading.Lock()
56
+ _stop = threading.Event()
57
 
58
+
59
+ def log(message):
60
+ print(f"[sync {time.strftime('%H:%M:%S')}] {message}", flush=True)
61
+
62
+
63
+ def bucket_url(prefix):
64
+ return f"hf://buckets/{BUCKET_ID}/{prefix}"
65
+
66
+
67
+ def ensure_bucket():
68
+ if not CREATE_BUCKET:
69
  return
 
 
70
  try:
71
+ api.create_bucket(BUCKET_ID, private=True, exist_ok=True, token=TOKEN)
72
+ log(f"bucket ready: {BUCKET_ID} (private)")
73
+ except Exception as exc:
74
+ log(f"could not create bucket (assuming it exists): {exc}")
75
+
76
+
77
+ def pull():
78
+ if not BUCKET_ID:
79
+ log("BUCKET_REPO_ID not set - skipping pull")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  return
81
+ for prefix, local, _ignore in TREES:
82
+ local.mkdir(parents=True, exist_ok=True)
83
+ try:
84
+ api.sync_bucket(
85
+ source=bucket_url(prefix),
86
+ dest=str(local),
87
+ token=TOKEN,
88
+ quiet=True,
89
+ )
90
+ log(f"pulled {prefix} -> {local}")
91
+ except Exception as exc:
92
+ log(f"pull {prefix} failed: {exc}")
93
+
94
+
95
+ def push():
96
+ if not BUCKET_ID:
97
+ return True
98
+ ok = True
99
+ for prefix, local, ignore in TREES:
100
+ if not local.exists():
101
+ continue
102
+ try:
103
+ api.sync_bucket(
104
+ source=str(local),
105
+ dest=bucket_url(prefix),
106
+ delete=True,
107
+ exclude=ignore,
108
+ token=TOKEN,
109
+ quiet=True,
110
+ )
111
+ log(f"pushed {prefix}")
112
+ except Exception as exc:
113
+ log(f"push {prefix} failed: {exc}")
114
+ ok = False
115
+ return ok
116
+
117
+
118
+ def full_sync():
119
+ if not _lock.acquire(blocking=False):
120
+ log("previous sync still running - skipping this tick")
121
+ return True
122
+ try:
123
+ return push()
124
+ finally:
125
+ _lock.release()
126
+
127
+
128
+ def handle_signal(signum, _frame):
129
+ log(f"signal {signum} - flushing to bucket before exit")
130
+ _stop.set()
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser()
135
+ parser.add_argument("--pull", action="store_true", help="one-shot bucket -> disk")
136
+ parser.add_argument("--push", action="store_true", help="one-shot disk -> bucket")
137
+ args = parser.parse_args()
138
+
139
+ if not BUCKET_ID:
140
+ log("BUCKET_REPO_ID is empty - sync daemon disabled")
141
+ return 0
142
+
143
+ ensure_bucket()
144
+
145
+ if args.pull:
146
+ pull()
147
+ return 0
148
+ if args.push:
149
+ return 0 if push() else 1
150
+
151
+ signal.signal(signal.SIGTERM, handle_signal)
152
+ signal.signal(signal.SIGINT, handle_signal)
153
+
154
+ log(f"daemon started: interval {INTERVAL}s, bucket {BUCKET_ID}")
155
+ failures = 0
156
+ while not _stop.is_set():
157
+ wait = INTERVAL if failures == 0 else min(INTERVAL * 2 ** failures, 600)
158
+ if _stop.wait(wait):
159
+ break
160
+ failures = 0 if full_sync() else failures + 1
161
+ if failures:
162
+ log(f"{failures} consecutive failure(s)")
163
+
164
+ full_sync()
165
+ log("flushed - bye")
166
+ return 0
167
+
168
 
169
  if __name__ == "__main__":
170
+ sys.exit(main())