amangs commited on
Commit
6cba4f0
·
1 Parent(s): 01d281b

Ship pre-fixed opencode index.html instead of sed-rewriting it at boot

Browse files

- config/opencode-router/index.html is now the source of truth; entrypoint and
20-opencode-router.sh just copy it (no more 6-line sed chain per boot).
- Router proxy key is injected into the HTML from opencode-router.json at start,
so no secret lives in the committed HTML.
- Run hermes-web-ui with NODE_ENV=production so its SQLite lands in
HERMES_WEB_UI_HOME (local disk, apps_sync-backed) instead of
$CWD/packages/server/data (the /data/workspace bucket).
- entrypoint migrates any existing workspace/packages/hermes-web-ui.db to
/home/appuser/.hermes-web-ui and drops the bucket-side tree.
- entrypoint migrates legacy /data/config dsh+opencode into /data/apps/
(removed only when byte-identical) and drops the legacy /data/code-server tree.
- code-server: seed ~/.config/code-server/config.yaml at runtime, purge
workspaceStorage after apps_sync restore so /code/ always opens blank,
point CachedData/ProfilesData/logs at /tmp.

Dockerfile CHANGED
@@ -167,7 +167,9 @@ RUN pip3 install --no-cache-dir --break-system-packages -r /tmp/requirements.txt
167
  # ------------------------------------------
168
  # 9. code-server
169
  # ------------------------------------------
170
- RUN curl -fsSL https://code-server.dev/install.sh | sh
 
 
171
 
172
  # ------------------------------------------
173
  # 10. goFiles & opencode-router
 
167
  # ------------------------------------------
168
  # 9. code-server
169
  # ------------------------------------------
170
+ RUN curl -fsSL https://code-server.dev/install.sh | sh && \
171
+ mkdir -p /root/.config/code-server && \
172
+ printf "bind-addr: 127.0.0.1:8443\nauth: password\ncert: false\n" > /root/.config/code-server/config.yaml
173
 
174
  # ------------------------------------------
175
  # 10. goFiles & opencode-router
config/Caddyfile.example CHANGED
@@ -22,13 +22,13 @@
22
  reverse_proxy 127.0.0.1:8093
23
  }
24
 
25
- # 2. code-server routing (/code)
26
- @code_noslash path /code
27
- redir @code_noslash /code/ 308
28
 
29
- handle_path /code/* {
30
- reverse_proxy 127.0.0.1:8443
31
- }
32
 
33
  # 3. goFiles file manager (/files -> mounted at /data)
34
  @files_noslash path /files
 
22
  reverse_proxy 127.0.0.1:8093
23
  }
24
 
25
+ # 2. code-server routing (/code)
26
+ @code_noslash path /code
27
+ redir @code_noslash /code/ 308
28
 
29
+ handle_path /code/* {
30
+ reverse_proxy 127.0.0.1:8443
31
+ }
32
 
33
  # 3. goFiles file manager (/files -> mounted at /data)
34
  @files_noslash path /files
config/opencode-router/index.html ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Router — High-Performance Model Router</title>
7
+ <link rel="icon" href="assets/logo.svg?v=9">
8
+ <style>
9
+ :root {
10
+ --paper:#f8fafc;
11
+ --paper2:#f1f5f9;
12
+ --card:#ffffff;
13
+ --ink:#0f172a;
14
+ --ink2:#334155;
15
+ --acid:#10b981;
16
+ --coral:#ef4444;
17
+ --grape:#0284c7;
18
+ --sky:#0ea5e9;
19
+ --muted:#64748b;
20
+ --line:1.5px solid #cbd5e1;
21
+ --sans:"Helvetica Neue",Helvetica,"Segoe UI",Arial,sans-serif;
22
+ --mono:ui-monospace,"SF Mono","Cascadia Code",Menlo,Consolas,monospace;
23
+ --serif:"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;
24
+ --spring:cubic-bezier(.34,1.56,.64,1);
25
+ --smooth:cubic-bezier(.16,1,.3,1);
26
+ }
27
+ * { box-sizing:border-box; margin:0; padding:0 }
28
+ html,body { min-height:100% }
29
+ body {
30
+ font-family:var(--sans); background:var(--paper); color:var(--ink);
31
+ font-size:14px; line-height:1.5; overflow-x:hidden;
32
+ background-image:radial-gradient(rgba(26,22,18,.09) 1px, transparent 1.3px);
33
+ background-size:22px 22px;
34
+ }
35
+ a { color:var(--ink) }
36
+
37
+ /* ---------- soft ink-wash blobs + grain ---------- */
38
+ .blobs { position:fixed; inset:0; z-index:-1; overflow:hidden; pointer-events:none }
39
+ .blob { position:absolute; border-radius:50%; filter:blur(70px); will-change:transform; contain:strict }
40
+ .b1 { width:52vmax; height:52vmax; left:-14vmax; top:-18vmax; background:radial-gradient(#bae6fd,transparent 65%); opacity:.35; animation:drift1 26s ease-in-out infinite alternate }
41
+ .b2 { width:46vmax; height:46vmax; right:-15vmax; top:2vmax; background:radial-gradient(#d1fae5,transparent 65%); opacity:.3; animation:drift2 30s ease-in-out infinite alternate }
42
+ .b3 { width:48vmax; height:48vmax; left:16vmax; bottom:-24vmax; background:radial-gradient(#e0e7ff,transparent 65%); opacity:.3; animation:drift3 34s ease-in-out infinite alternate }
43
+ .b4 { width:34vmax; height:34vmax; right:20vmax; bottom:-12vmax; background:radial-gradient(#e2e8f0,transparent 65%); opacity:.35; animation:drift4 22s ease-in-out infinite alternate }
44
+ @keyframes drift1 { to { transform:translate(9vmax,6vmax) scale(1.15) } }
45
+ @keyframes drift2 { to { transform:translate(-8vmax,8vmax) scale(1.2) } }
46
+ @keyframes drift3 { to { transform:translate(6vmax,-7vmax) scale(1.1) } }
47
+ @keyframes drift4 { to { transform:translate(-7vmax,-6vmax) scale(1.25) } }
48
+ .grain { position:fixed; inset:0; z-index:70; pointer-events:none; opacity:.05;
49
+ background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='300'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.55'/%3E%3C/svg%3E");
50
+ background-size:300px 300px }
51
+ @media (prefers-reduced-motion: reduce) { .blob { animation:none } }
52
+
53
+ /* ---------- header ---------- */
54
+ header {
55
+ position:sticky; top:0; z-index:40;
56
+ display:flex; align-items:center; gap:14px;
57
+ max-width:1120px; margin:0 auto; padding:14px 18px;
58
+ background:rgba(255,255,255,.94); border-bottom:var(--line);
59
+ -webkit-backdrop-filter:blur(10px); backdrop-filter:blur(10px);
60
+ }
61
+ .brand { display:flex; align-items:center; gap:10px; white-space:nowrap }
62
+ .brand .logo {
63
+ width:34px; height:34px; display:block; object-fit:contain;
64
+ border-radius:8px; border:1px solid #334155;
65
+ box-shadow:0 2px 5px rgba(0,0,0,0.12);
66
+ background:#090d16;
67
+ }
68
+ .brand .txt { font-family:var(--mono); font-weight:800; font-size:14px; letter-spacing:.08em }
69
+ nav.capsule {
70
+ position:relative; display:flex; align-items:center; gap:6px; padding:5px 6px; flex:1; min-width:0;
71
+ background:var(--paper2); border:var(--line); border-radius:999px;
72
+ overflow-x:auto; scrollbar-width:none;
73
+ }
74
+ nav.capsule::-webkit-scrollbar { display:none }
75
+ .nav-indicator {
76
+ position:absolute; top:5px; left:0; height:calc(100% - 10px); border-radius:999px;
77
+ background:#0284c7; border:none;
78
+ box-shadow:0 2px 6px rgba(2,132,199,0.3);
79
+ transition:transform .5s var(--spring), width .5s var(--spring);
80
+ pointer-events:none; z-index:0;
81
+ }
82
+ nav button {
83
+ position:relative; z-index:1; flex:0 0 auto; border:none; cursor:pointer;
84
+ background:transparent; color:var(--muted);
85
+ padding:8px 18px; border-radius:999px;
86
+ font-family:var(--mono); font-weight:800; font-size:11.5px; letter-spacing:.1em; text-transform:uppercase;
87
+ transition:color .25s, transform .25s var(--spring);
88
+ }
89
+ nav button:hover { color:var(--ink) }
90
+ nav button:active { transform:scale(.92) }
91
+ nav button.active { color:#ffffff }
92
+ .pill {
93
+ display:inline-flex; align-items:center; gap:8px; padding:7px 14px; white-space:nowrap;
94
+ background:#ffffff; border:1.5px solid #cbd5e1; border-radius:999px;
95
+ box-shadow:0 1px 3px rgba(0,0,0,0.05);
96
+ font-family:var(--mono); font-weight:700; font-size:11px; letter-spacing:.06em; text-transform:uppercase;
97
+ color:#334155;
98
+ }
99
+ .pill .dot { width:9px; height:9px; border-radius:50%; background:#94a3b8; transition:all .2s }
100
+ .dot.ok { background:#10b981; box-shadow:0 0 0 3px #d1fae5, 0 0 8px #10b981 }
101
+ .dot.bad { background:#ef4444; box-shadow:0 0 0 3px #fee2e2, 0 0 8px #ef4444 }
102
+
103
+ /* ---------- marquee strip ---------- */
104
+ .marquee {
105
+ position:relative; max-width:1084px; margin:20px auto 0; overflow:hidden;
106
+ border:var(--line); background:#ffffff; color:#0284c7;
107
+ border-radius:10px; box-shadow:0 2px 6px rgba(15,23,42,0.06);
108
+ }
109
+ .mq-track {
110
+ display:flex; width:max-content; animation:mq 26s linear infinite; will-change:transform;
111
+ font-family:var(--mono); font-weight:800; font-size:11.5px; letter-spacing:.16em; text-transform:uppercase;
112
+ white-space:nowrap; padding:7px 0;
113
+ }
114
+ .mq-track span { padding:0 18px }
115
+ @keyframes mq { to { transform:translateX(-50%) } }
116
+ @media (prefers-reduced-motion: reduce) { .mq-track { animation:none } }
117
+
118
+ main { max-width:1120px; margin:28px auto 70px; padding:0 18px }
119
+ .banner {
120
+ display:none; max-width:1084px; margin:22px auto 0; padding:13px 18px;
121
+ border:var(--line); background:var(--coral); color:#fff;
122
+ font-family:var(--mono); font-weight:800; font-size:12px; letter-spacing:.06em; text-transform:uppercase;
123
+ box-shadow:5px 5px 0 var(--ink); transform:rotate(-.4deg);
124
+ }
125
+ .banner.error { display:block }
126
+
127
+ /* ---------- liquid tab transitions ---------- */
128
+ .tab { display:none }
129
+ .tab.active { display:block; animation:tabIn .55s var(--smooth) }
130
+ .tab.leaving { display:block; animation:tabOut .34s ease forwards; pointer-events:none }
131
+ @keyframes tabIn { from { opacity:0; transform:translateY(20px) rotate(.5deg) scale(.985); filter:blur(8px) } to { opacity:1; transform:none; filter:none } }
132
+ @keyframes tabOut { to { opacity:0; transform:translateY(-14px) rotate(-.4deg); filter:blur(6px) } }
133
+ @media (prefers-reduced-motion: reduce) { .tab.active { animation:none } }
134
+
135
+ /* ---------- cards ---------- */
136
+ .cards { display:grid; grid-template-columns:repeat(5,1fr); gap:16px; margin-bottom:24px }
137
+ @media (max-width:1000px) { .cards { grid-template-columns:repeat(3,1fr) } }
138
+ @media (max-width:760px) { .cards { grid-template-columns:repeat(2,1fr) } }
139
+ @media (max-width:460px) { .cards { grid-template-columns:1fr } }
140
+ .card {
141
+ position:relative; padding:20px; min-width:0;
142
+ background:var(--card); border:var(--line); border-radius:22px 8px 22px 8px;
143
+ box-shadow:8px 8px 0 var(--ink);
144
+ transform:rotate(var(--tilt,0));
145
+ transition:transform .35s var(--smooth), box-shadow .35s var(--smooth);
146
+ }
147
+ .card:nth-child(odd) { --tilt:-.7deg }
148
+ .card:nth-child(even) { --tilt:.6deg }
149
+ .card:hover { transform:translateY(-4px) rotate(0deg); box-shadow:12px 12px 0 var(--ink) }
150
+ .card .label {
151
+ font-family:var(--mono); font-size:10px; font-weight:800; color:var(--muted);
152
+ text-transform:uppercase; letter-spacing:.14em; display:flex; align-items:center; gap:6px;
153
+ }
154
+ .card .label::before { content:"◦" }
155
+ .card .value { font-size:34px; font-weight:900; margin-top:10px; letter-spacing:-.045em; font-variant-numeric:tabular-nums; text-transform:uppercase }
156
+ .card .value.mono { font-size:14px; letter-spacing:0; text-transform:none; font-weight:800; overflow-wrap:anywhere; word-break:break-word; line-height:1.4 }
157
+ .card .sub { font-family:var(--mono); font-size:10.5px; color:var(--muted); margin-top:8px; text-transform:uppercase; letter-spacing:.08em }
158
+ .cards .card.hero {
159
+ background: #0f172a;
160
+ border: 1.5px solid #1e293b;
161
+ box-shadow: 0 4px 14px rgba(15, 23, 42, 0.12);
162
+ color: #ffffff;
163
+ }
164
+ .cards .card.hero .label { color: #94a3b8; font-weight: 700; }
165
+ .cards .card.hero .label::before { color: #38bdf8; }
166
+ .cards .card.hero .value { color: #ffffff; font-weight: 900; }
167
+ .cards .card.hero .sub { color: #38bdf8; font-weight: 600; }
168
+ .cards .card.hero:hover { box-shadow: 0 8px 20px rgba(15, 23, 42, 0.25); }
169
+
170
+ /* ---------- panels ---------- */
171
+ .panel {
172
+ position:relative; padding:26px; margin-bottom:24px;
173
+ background:var(--card); border:var(--line); border-radius:26px 10px 26px 10px;
174
+ box-shadow:9px 9px 0 var(--ink);
175
+ }
176
+ .panel h2 {
177
+ display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;
178
+ font-family:var(--mono); font-size:12.5px; font-weight:800; letter-spacing:.14em; text-transform:uppercase;
179
+ }
180
+ .panel h2 .hh {
181
+ padding:0 8px; background:linear-gradient(transparent 62%, rgba(204,247,58,.85) 62%);
182
+ }
183
+ .hint { font-family:var(--mono); font-size:11.5px; color:var(--muted); margin-top:8px; line-height:1.7 }
184
+ code { background:rgba(26,22,18,.08); padding:1px 5px; border-radius:4px; font-family:var(--mono); font-size:.95em }
185
+
186
+ /* ---------- table ---------- */
187
+ table { width:100%; border-collapse:collapse; font-variant-numeric:tabular-nums }
188
+ th,td { text-align:left; padding:12px 12px; border-bottom:var(--line); font-size:13px }
189
+ th { font-family:var(--mono); font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:.12em; color:var(--muted) }
190
+ td { border-bottom:1px dashed rgba(26,22,18,.35) }
191
+ tbody tr { transition:background .18s }
192
+ tbody tr:hover { background:rgba(204,247,58,.25) }
193
+ tbody tr:last-child td { border-bottom:none }
194
+ .mono { font-family:var(--mono); font-size:12.5px }
195
+ .badge { display:inline-block; padding:2.5px 9px; border-radius:999px; font-family:var(--mono); font-size:10.5px; font-weight:700; letter-spacing:.04em; text-transform:uppercase }
196
+ .badge.ok { background:#ecfdf5; color:#047857; border:1px solid #a7f3d0 }
197
+ .badge.bad { background:#fef2f2; color:#b91c1c; border:1px solid #fecaca }
198
+ .badge.warn { background:#fffbeb; color:#b45309; border:1px solid #fde68a }
199
+ .badge.mut { background:#f1f5f9; color:#475569; border:1px solid #cbd5e1 }
200
+
201
+ /* Tooltip — purpose-built for this dashboard. Sticker-card look that reuses the
202
+ same ink border + hard offset shadow as the badges and buttons, a two-tone
203
+ pointer so it reads as attached, and a spring entrance. Auto-width, so the
204
+ copy can never overflow, and it flips below the trigger near the top edge.
205
+ Zero dependencies. */
206
+ [data-tip] { position:relative; cursor:help }
207
+ [data-tip]:focus-visible { outline:2px solid var(--ink); outline-offset:2px }
208
+ .ztip {
209
+ position:absolute; left:50%; bottom:calc(100% + 11px);
210
+ width:max-content; max-width:250px;
211
+ padding:8px 12px 9px;
212
+ background:var(--paper); color:var(--ink);
213
+ border:2px solid var(--ink); border-radius:10px;
214
+ box-shadow:3px 3px 0 var(--ink);
215
+ text-align:left; pointer-events:none; z-index:70;
216
+ opacity:0; visibility:hidden;
217
+ transform:translate(-50%, 5px) scale(.96); transform-origin:50% 100%;
218
+ transition:opacity .15s ease, transform .2s cubic-bezier(.34,1.35,.64,1), visibility 0s linear .2s;
219
+ }
220
+ .ztip.open { opacity:1; visibility:visible; transform:translate(-50%,0) scale(1); transition-delay:0s }
221
+ .ztip-title {
222
+ display:flex; align-items:center; gap:6px; flex-wrap:wrap;
223
+ font-family:var(--mono); font-size:9.5px; font-weight:800;
224
+ letter-spacing:.09em; text-transform:uppercase; color:var(--ztip-accent, var(--ink));
225
+ overflow-wrap:anywhere;
226
+ }
227
+ .ztip-title::before {
228
+ content:""; width:8px; height:8px; flex:none;
229
+ background:var(--ztip-accent, var(--ink)); border:1.5px solid var(--ink); border-radius:2px;
230
+ }
231
+ .ztip-body { margin-top:4px; font-family:var(--sans); font-size:12px; line-height:1.45; color:var(--ink); overflow-wrap:anywhere; max-height:150px; overflow-y:auto }
232
+ /* pointer: ink triangle with a paper triangle layered on top for a bordered join */
233
+ .ztip::before, .ztip::after {
234
+ content:""; position:absolute; left:50%; width:0; height:0;
235
+ border-left:7px solid transparent; border-right:7px solid transparent;
236
+ }
237
+ .ztip::after { top:100%; transform:translateX(-50%); border-top:9px solid var(--ink); z-index:0 }
238
+ .ztip::before { top:100%; z-index:1; transform:translateX(-50%) translateY(-2px); border-top:6px solid var(--paper) }
239
+ .ztip.below { bottom:auto; top:calc(100% + 11px); transform:translate(-50%,-5px) scale(.96); transform-origin:50% 0 }
240
+ .ztip.below.open { transform:translate(-50%,0) scale(1) }
241
+ .ztip.below::after { top:auto; bottom:100%; border-top:0; border-bottom:9px solid var(--ink) }
242
+ .ztip.below::before { top:auto; bottom:100%; border-top:0; border-bottom:6px solid var(--paper); transform:translateX(-50%) translateY(2px) }
243
+ @media (prefers-reduced-motion: reduce) { .ztip { transition:none } }
244
+
245
+ .empty { font-family:var(--serif); font-style:italic; color:var(--muted); text-align:center; padding:38px; font-size:15px }
246
+ .pager { display:flex; align-items:center; justify-content:flex-end; gap:12px; margin-top:16px }
247
+ .pager button { padding:6px 13px; font-size:10.5px; box-shadow:3px 3px 0 var(--ink) }
248
+ .pager button:active { box-shadow:0 0 0 var(--ink) }
249
+ .pager-info { font-family:var(--mono); font-size:11px; font-weight:800; color:var(--muted); letter-spacing:.06em; text-transform:uppercase; white-space:nowrap }
250
+
251
+ /* ---------- controls ---------- */
252
+ button {
253
+ background:var(--ink); color:var(--card); border:2px solid var(--ink);
254
+ padding:9px 16px; border-radius:10px; cursor:pointer;
255
+ font-family:var(--mono); font-weight:800; font-size:11px; letter-spacing:.1em; text-transform:uppercase;
256
+ box-shadow:4px 4px 0 var(--ink);
257
+ transition:transform .2s var(--spring), box-shadow .2s, background .2s, color .2s;
258
+ }
259
+ button:hover { transform:translate(-1px,-1px); box-shadow:6px 6px 0 var(--ink) }
260
+ button:active { transform:translate(2px,2px); box-shadow:0 0 0 var(--ink) }
261
+ button:disabled { opacity:.45; cursor:not-allowed; transform:none; box-shadow:4px 4px 0 var(--ink) }
262
+ button.primary { background:#0284c7; color:#ffffff; border:1.5px solid #0284c7; box-shadow:0 2px 6px rgba(2,132,199,0.25); }
263
+ button.primary:hover { background:#0369a1; border-color:#0369a1; color:#ffffff; }
264
+ button.primary:hover { box-shadow:7px 7px 0 var(--ink) }
265
+ input, select, textarea {
266
+ background:#fff; color:var(--ink); border:2px solid var(--ink); border-radius:10px;
267
+ padding:11px 13px; font-size:13.5px; width:100%; font-family:var(--sans);
268
+ transition:box-shadow .2s, background .2s;
269
+ }
270
+ input:focus, select:focus, textarea:focus { outline:none; box-shadow:0 0 0 3px var(--acid) }
271
+ label {
272
+ display:block; font-family:var(--mono); font-size:10.5px; font-weight:800; color:var(--ink2);
273
+ margin:16px 0 7px; text-transform:uppercase; letter-spacing:.12em;
274
+ }
275
+ label::before { content:"▸ "; color:var(--coral) }
276
+ /* ---------- endpoint card ---------- */
277
+ .endpoint-card {
278
+ display:flex; align-items:center; gap:10px;
279
+ background:#ffffff; border:1px solid #cbd5e1; border-radius:10px;
280
+ padding:8px 12px; margin-bottom:16px; box-shadow:0 1px 3px rgba(15,23,42,0.04);
281
+ box-sizing:border-box; width:100%;
282
+ }
283
+ .endpoint-tag {
284
+ background:#e0f2fe; color:#0369a1; border:1px solid #bae6fd;
285
+ font-family:var(--mono); font-weight:800; font-size:9.5px; letter-spacing:.05em;
286
+ padding:3px 6px; border-radius:4px; flex:0 0 auto; white-space:nowrap;
287
+ }
288
+ .endpoint-val {
289
+ font-family:var(--mono); font-size:12px; font-weight:700; color:#0f172a;
290
+ white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
291
+ flex:1; min-width:0; user-select:all;
292
+ }
293
+ .endpoint-copy-btn {
294
+ flex:0 0 auto; font-size:11px; padding:5px 12px; border-radius:6px;
295
+ white-space:nowrap; cursor:pointer; line-height:1.2;
296
+ }
297
+
298
+ /* ---------- settings sections ---------- */
299
+ .cfg-section {
300
+ background:#ffffff; border:1px solid #e2e8f0; border-radius:14px;
301
+ padding:18px 20px; margin-bottom:18px; box-shadow:0 1px 3px rgba(15,23,42,0.03);
302
+ }
303
+ .cfg-section-title {
304
+ display:flex; align-items:center; justify-content:space-between;
305
+ font-family:var(--mono); font-size:11px; font-weight:800; text-transform:uppercase;
306
+ letter-spacing:.08em; color:var(--ink); margin-bottom:12px; padding-bottom:8px;
307
+ border-bottom:1px dashed #cbd5e1;
308
+ }
309
+ .cfg-section-title span.tag {
310
+ font-size:9.5px; padding:2px 7px; border-radius:4px;
311
+ background:#f1f5f9; color:#64748b; border:1px solid #e2e8f0;
312
+ }
313
+ .formgrid { display:grid; grid-template-columns:repeat(auto-fit,minmax(250px,1fr)); gap:0 24px }
314
+ textarea { resize:vertical; min-height:96px; font-family:var(--mono); font-size:12.5px }
315
+ .row { display:flex; gap:12px; align-items:center; flex-wrap:wrap }
316
+ .row .grow { flex:1 }
317
+ .checkbox { display:flex; align-items:center; gap:10px; margin-top:18px }
318
+ .checkbox input { width:auto; accent-color:var(--coral) }
319
+ .checkbox span { font-size:13.5px }
320
+ .checkbox code { font-size:.9em }
321
+ .testCell { transition:color .2s; font-weight:700 }
322
+
323
+ /* ---------- logs ---------- */
324
+ .logs {
325
+ background:#15120d; border:var(--line); border-radius:14px; padding:16px; height:430px; overflow-y:auto;
326
+ font-family:var(--mono); font-size:12px; color:#e9e2d2;
327
+ box-shadow:inset 0 2px 18px rgba(0,0,0,.5);
328
+ }
329
+ .logs .ts { color:#8a806c; margin-right:14px }
330
+ .logs .line { white-space:pre-wrap; word-break:break-all; padding:3px 0 }
331
+ .logs .line:hover { background:rgba(204,247,58,.08) }
332
+
333
+ /* ---------- toast ---------- */
334
+ .toast {
335
+ position:fixed; bottom:26px; right:26px; z-index:60;
336
+ padding:15px 24px; border-radius:12px;
337
+ font-family:var(--mono); font-weight:800; font-size:12px; letter-spacing:.06em;
338
+ background:var(--ink); color:var(--card);
339
+ border:2px solid var(--ink); border-left:8px solid var(--acid);
340
+ box-shadow:6px 6px 0 var(--ink);
341
+ opacity:0; transform:translateY(12px) rotate(1deg); transition:.3s var(--spring); pointer-events:none;
342
+ }
343
+ .toast.show { opacity:1; transform:none }
344
+ .toast.bad { border-left-color:var(--coral) }
345
+
346
+ /* ---------- stickers ---------- */
347
+ .sticker {
348
+ display:inline-block; padding:7px 16px;
349
+ font-family:var(--mono); font-weight:800; font-size:10.5px; letter-spacing:.14em; text-transform:uppercase;
350
+ background:var(--acid); border:2px solid var(--ink); border-radius:999px;
351
+ box-shadow:4px 4px 0 var(--ink); transform:rotate(-4deg);
352
+ }
353
+ .sticker.coral { background:#fef2f2; color:#b91c1c; border:1px solid #fecaca; transform:none }
354
+ .sticker.grape { background:#e0f2fe; color:#0369a1; border:1px solid #bae6fd; transform:none }
355
+
356
+ /* ---------- auth ---------- */
357
+ #authScreen {
358
+ position:fixed; inset:0; z-index:100; display:none; align-items:center; justify-content:center;
359
+ background:rgba(26,22,18,.6); -webkit-backdrop-filter:blur(4px); backdrop-filter:blur(4px);
360
+ }
361
+ #authScreen .box { width:360px; padding:32px; background:var(--ink); color:var(--card);
362
+ border:2px solid var(--ink); border-radius:18px; box-shadow:12px 12px 0 var(--acid); animation:tabIn .5s var(--smooth) }
363
+ #authScreen h2 { font-family:var(--mono); font-size:15px; letter-spacing:.12em; text-transform:uppercase; margin-bottom:8px; color:var(--acid) }
364
+ #authScreen p { color:#c9c1ae; font-size:13px; margin-bottom:20px }
365
+ #authScreen .box input { background:#241f18; border-color:#4a4234; color:var(--card) }
366
+ #authScreen .box input:focus { box-shadow:0 0 0 3px var(--acid) }
367
+
368
+ @media (max-width:760px) {
369
+ .brand .txt { display:none }
370
+ header { padding:10px 14px; gap:8px }
371
+ nav button { padding:7px 12px; font-size:11px }
372
+ main { padding:0 12px }
373
+ }
374
+ @media (max-width:480px) {
375
+ header { padding:8px 10px; gap:6px }
376
+ nav button { padding:6px 9px; font-size:10px; letter-spacing:.04em }
377
+ #upstreamText { display:none }
378
+ .pill { padding:6px 8px }
379
+ }
380
+ </style>
381
+ </head>
382
+ <body>
383
+
384
+ <div class="blobs" aria-hidden="true">
385
+ <span class="blob b1"></span><span class="blob b2"></span><span class="blob b3"></span><span class="blob b4"></span>
386
+ </div>
387
+ <div class="grain" aria-hidden="true"></div>
388
+
389
+ <div id="authScreen" style="display:none">
390
+ <div class="box">
391
+ <img src="assets/logo.svg?v=9" alt="OpenCode Router logo" style="width:56px;height:56px;border-radius:14px;border:2px solid var(--acid);box-shadow:3px 3px 0 var(--coral);margin-bottom:16px;object-fit:cover">
392
+ <h2>Locked 🔒</h2>
393
+ <p>This dashboard is protected. Enter the admin key (<code>PROXY_KEY</code>) to get in.</p>
394
+ <input type="password" id="authKey" placeholder="admin key" autocomplete="off">
395
+ <div class="row" style="margin-top:20px">
396
+ <button class="primary grow" onclick="submitAuth()">Unlock</button>
397
+ </div>
398
+ </div>
399
+ </div>
400
+
401
+ <header>
402
+ <div class="brand"><img src="assets/logo.svg?v=9" alt="OpenCode Router logo" class="logo"><span class="txt">OPENCODE·ROUTER</span></div>
403
+ <nav class="capsule" id="nav">
404
+ <div class="nav-indicator" id="navIndicator"></div>
405
+ <button data-tab="overview" class="active">Overview</button>
406
+ <button data-tab="models">Models</button>
407
+ <button data-tab="config">Settings</button>
408
+ <button data-tab="logs">Logs</button>
409
+ </nav>
410
+ <span class="pill" id="upstreamPill"><span class="dot" id="upstreamDot"></span><span id="upstreamText">checking…</span></span>
411
+ </header>
412
+
413
+
414
+
415
+ <div class="banner" id="banner"></div>
416
+
417
+ <main>
418
+ <section class="tab active" id="tab-overview">
419
+ <!-- Dynamic Endpoint Banner -->
420
+ <div class="endpoint-card">
421
+ <span class="endpoint-tag">API BASE URL</span>
422
+ <span class="endpoint-val" id="endpointUrl" title="Click to copy">http://127.0.0.1:8790/v1</span>
423
+ <button type="button" class="primary endpoint-copy-btn" id="copyBtn" onclick="copyEndpoint()">Copy URL</button>
424
+ </div>
425
+ <div class="cards">
426
+ <div class="card hero"><div class="label">Requests served</div><div class="value" id="ovTotal">–</div><div class="sub" id="ovErr">0 errors</div></div>
427
+ <div class="card"><div class="label">Upstream</div><div class="value mono" id="ovUpstream">–</div><div class="sub" id="ovUa">–</div></div>
428
+ <div class="card"><div class="label">Uptime</div><div class="value" id="ovUptime">–</div><div class="sub">seconds online</div></div>
429
+ <div class="card"><div class="label">Last minute</div><div class="value" id="ovMin">–</div><div class="sub" id="ov5m">– in 5 min</div></div>
430
+ <div class="card"><div class="label">Models</div><div class="value" id="ovModels">–</div><div class="sub" id="ovAllowed">– allowed</div></div>
431
+ </div>
432
+
433
+ <div class="panel">
434
+ <h2><span class="hh">Recent requests</span><span style="display:inline-flex; align-items:center; gap:10px; margin-left:auto"><button style="font-size:10.5px; padding:4px 10px;" onclick="resetStats()">Clear stats</button><span class="sticker grape" style="transform:none">live feed</span></span></h2>
435
+ <table id="reqTable">
436
+ <thead><tr><th>Time</th><th>Model</th><th>Result</th><th>Latency</th><th>Count</th></tr></thead>
437
+ <tbody><tr><td colspan="5" class="empty">no requests yet — go make some noise.</td></tr></tbody>
438
+ </table>
439
+ <div class="pager" id="reqPager"></div>
440
+ </div>
441
+ </section>
442
+
443
+ <section class="tab" id="tab-models">
444
+ <div class="panel">
445
+ <h2><span class="hh">Allowed models</span><span class="badge mut" id="modelCount"></span></h2>
446
+ <p class="hint" style="margin-bottom:16px">These are served on <code>/v1/models</code> and accepted by the proxy. Hit <b>TEST</b> to send a tiny completion and see live status. The default model is used when a request asks for an unknown one. Auto-sync probes every upstream free model and prunes the dead ones automatically.</p>
447
+ <div class="row" style="margin:0 0 16px;gap:12px">
448
+ <span class="badge mut" id="syncStatus">auto-sync: …</span>
449
+ <button id="syncBtn" style="margin-left:auto" onclick="syncNow()">⟳ Sync now</button>
450
+ </div>
451
+ <div style="overflow-x:auto;margin:0 -4px;padding:0 4px">
452
+ <table id="modelTable" style="width:100%;min-width:680px">
453
+ <thead>
454
+ <tr>
455
+ <th style="width:44%">Model</th>
456
+ <th style="width:10%;text-align:center">Default</th>
457
+ <th style="width:34%">Last test</th>
458
+ <th style="width:12%;text-align:right;padding-right:16px">Actions</th>
459
+ </tr>
460
+ </thead>
461
+ <tbody></tbody>
462
+ </table>
463
+ </div>
464
+ <div class="row" style="margin-top:18px">
465
+ <input class="grow" id="newModel" placeholder="add a model id, e.g. nemotron-3-ultra-free">
466
+ <button onclick="addModel()">+ Add</button>
467
+ </div>
468
+ </div>
469
+ </section>
470
+
471
+ <section class="tab" id="tab-config">
472
+ <div class="panel">
473
+ <h2><span class="hh">Server settings</span><span class="sticker coral" style="transform:none">port / host need restart</span></h2>
474
+
475
+ <!-- Section 1: Network & Server -->
476
+ <div class="cfg-section">
477
+ <div class="cfg-section-title">
478
+ <span>Network &amp; Connectivity</span>
479
+ <span class="tag">Core</span>
480
+ </div>
481
+ <div class="formgrid">
482
+ <div>
483
+ <label>Host</label><input id="cfgHost" type="text">
484
+ <label>Port</label><input id="cfgPort" type="number">
485
+ <label>Upstream URL</label><input id="cfgUpstream" type="text">
486
+ </div>
487
+ <div>
488
+ <label>Outbound proxy <span class="hint">(socks5://[user:pass@]host:port or http://)</span></label><input id="cfgOutboundProxy" type="text" placeholder="e.g. socks5://127.0.0.1:1080">
489
+ <label>User-agent (the unlock)</label><input id="cfgUa" type="text">
490
+ <div class="checkbox"><input type="checkbox" id="cfgTrust"><span>Trust <code>x-forwarded-for</code> from a reverse proxy</span></div>
491
+ </div>
492
+ </div>
493
+ </div>
494
+
495
+ <!-- Section 2: Security & Access -->
496
+ <div class="cfg-section">
497
+ <div class="cfg-section-title">
498
+ <span>Security &amp; Rate Limiting</span>
499
+ <span class="tag">Access</span>
500
+ </div>
501
+ <div class="formgrid">
502
+ <div>
503
+ <label>Proxy key (empty = open)</label><input id="cfgProxyKey" type="password" autocomplete="new-password">
504
+ <div class="checkbox"><input type="checkbox" id="cfgInject"><span>Inject <code>x-opencode-session</code> header per client (free tier needs it)</span></div>
505
+ </div>
506
+ <div>
507
+ <label>Upstream Key (BYOK, optional)</label><input id="cfgUpstreamKey" type="password" autocomplete="new-password">
508
+ <div class="row" style="gap:8px;margin-top:2px">
509
+ <button type="button" class="primary" onclick="testUpstreamKey()" style="font-size:11px;padding:6px 10px">Test key</button>
510
+ <span class="hint mono" id="cfgAuth"></span>
511
+ <span class="hint" id="upstreamKeyHint" style="min-height:16px"></span>
512
+ </div>
513
+ </div>
514
+ </div>
515
+ <div style="margin-top:14px;border-top:1px dashed #e2e8f0;padding-top:10px">
516
+ <div class="checkbox"><input type="checkbox" id="cfgRateLimit"><span>Rate-limit chat requests per client (0 = off)</span></div>
517
+ <div class="row" style="gap:10px;margin-top:6px">
518
+ <div><label>Requests / window</label><input id="cfgRateMax" type="number" min="0" style="width:120px"></div>
519
+ <div><label>Window (ms)</label><input id="cfgRateWindow" type="number" min="1000" style="width:140px"></div>
520
+ </div>
521
+ </div>
522
+ </div>
523
+
524
+ <!-- Section 3: Model Routing & Formats -->
525
+ <div class="cfg-section">
526
+ <div class="cfg-section-title">
527
+ <span>Model Routing &amp; Rules</span>
528
+ <span class="tag">Routing</span>
529
+ </div>
530
+ <div class="formgrid">
531
+ <div>
532
+ <label>Default model <span class="hint">(empty = auto-pick healthy free model)</span></label><input id="cfgDefault" type="text">
533
+ </div>
534
+ <div>
535
+ <label>Timeout (ms)</label><input id="cfgTimeout" type="number">
536
+ </div>
537
+ </div>
538
+ <label>Responses-API models (json array — patterns may end in *)</label>
539
+ <textarea id="cfgResponses" style="min-height:70px"></textarea>
540
+ <label>Model aliases (json map — e.g. {"gpt-4o":"space-bunny-free"})</label>
541
+ <textarea id="cfgAliases" style="min-height:70px"></textarea>
542
+ <label>Fallback models (json array — tried in order on 429/5xx)</label>
543
+ <textarea id="cfgFallback" style="min-height:70px"></textarea>
544
+ </div>
545
+
546
+ <!-- Section 4: Health Probes, Metadata & Sync -->
547
+ <div class="cfg-section">
548
+ <div class="cfg-section-title">
549
+ <span>Health Probes &amp; Auto-Sync</span>
550
+ <span class="tag">Automation</span>
551
+ </div>
552
+ <label>Health-probe credentials</label>
553
+ <select id="cfgProbeAuth" style="width:100%">
554
+ <option value="auto">Auto — use Upstream Key if set, else anonymous</option>
555
+ <option value="anonymous">Always anonymous (public free tier)</option>
556
+ <option value="key">Always Upstream Key (tests own quota)</option>
557
+ </select>
558
+ <div class="formgrid" style="margin-top:10px">
559
+ <div>
560
+ <div class="checkbox"><input type="checkbox" id="cfgAutoSync"><span>Auto-sync models (probe upstream free models, prune dead ones)</span></div>
561
+ <label>Auto-sync interval (ms)</label><input id="cfgSyncMs" type="number">
562
+ </div>
563
+ <div>
564
+ <div class="checkbox"><input type="checkbox" id="cfgAutoUA"><span>Auto-track opencode releases &amp; update User-Agent</span></div>
565
+ <label>User-agent refresh interval (days)</label><input id="cfgUaDays" type="number" step="0.5" min="0.1">
566
+ </div>
567
+ </div>
568
+ <div style="margin-top:14px;border-top:1px dashed #e2e8f0;padding-top:10px">
569
+ <label>Models metadata endpoint URL</label>
570
+ <input id="cfgMetaEndpoint" type="text" placeholder="https://models.dev/api.json">
571
+ <div class="row" style="gap:10px;margin-top:4px">
572
+ <div style="flex:1">
573
+ <label>Metadata request timeout (seconds)</label>
574
+ <input id="cfgMetaTimeout" type="number" min="5" max="120" placeholder="30">
575
+ </div>
576
+ <div style="flex:1">
577
+ <label>Metadata sync interval (hours)</label>
578
+ <input id="cfgMetaSyncHours" type="number" min="1" max="168" placeholder="24">
579
+ </div>
580
+ </div>
581
+ <div class="hint" style="margin-top:-2px;margin-bottom:6px">Pulls model specs, context limits, and modalities to <code>models-dev-cache.json</code>.</div>
582
+ </div>
583
+ </div>
584
+
585
+ <!-- Action buttons -->
586
+ <div class="row" style="margin-top:22px">
587
+ <button class="primary" onclick="saveConfig()">Save &amp; apply</button>
588
+ <button onclick="reloadConfig()">Discard / reload</button>
589
+ <button onclick="restoreModels()" title="Re-add any model the proxy is missing (keeps your keys)">Restore model list</button>
590
+ </div>
591
+ </div>
592
+ </section>
593
+
594
+ <section class="tab" id="tab-logs">
595
+ <div class="panel">
596
+ <h2><span class="hh">Server logs</span><button style="font-size:10.5px; padding:6px 12px" onclick="loadLogs()">Refresh</button></h2>
597
+ <div class="logs" id="logBox"><div class="empty">Loading…</div></div>
598
+ </div>
599
+ </section>
600
+ </main>
601
+
602
+ <div class="toast" id="toast"></div>
603
+
604
+ <script>
605
+ const $ = (id) => document.getElementById(id)
606
+ let key = localStorage.getItem("opencodeKey") || ""
607
+ let config = null, manualTests = {}
608
+ let savedUpstreamKeyMasked = ""
609
+
610
+ const basePath = window.location.pathname.replace(/\/+$/, '');
611
+ function api(path, opts = {}) {
612
+ const targetPath = basePath + (path.startsWith('/') ? path : '/' + path);
613
+ const headers = { ...(opts.headers || {}) }
614
+ if (key) headers["Authorization"] = "Bearer " + key
615
+ if (opts.body) headers["Content-Type"] = "application/json"
616
+ return fetch(targetPath, { ...opts, headers }).then(async (r) => {
617
+ if (r.status === 401) { showAuth(); throw new Error("unauthorized") }
618
+ return r.json()
619
+ })
620
+ }
621
+
622
+ function toast(msg, type = "ok") {
623
+ const t = $("toast")
624
+ t.textContent = msg
625
+ t.className = "toast show " + type
626
+ clearTimeout(t._h)
627
+ t._h = setTimeout(() => (t.className = "toast"), 2400)
628
+ }
629
+ function showBanner(msg) { const b = $("banner"); b.textContent = msg; b.className = "banner error" }
630
+ function hideBanner() { $("banner").className = "banner" }
631
+
632
+ function showAuth() {
633
+ $("authScreen").style.display = "flex"
634
+ $("authKey").focus()
635
+ }
636
+ async function submitAuth() {
637
+ key = $("authKey").value.trim()
638
+ localStorage.setItem("opencodeKey", key)
639
+ try {
640
+ await api("/api/status")
641
+ $("authScreen").style.display = "none"
642
+ toast("Unlocked")
643
+ refreshAll()
644
+ } catch {
645
+ toast("Wrong key", "bad")
646
+ key = ""
647
+ localStorage.removeItem("opencodeKey")
648
+ }
649
+ }
650
+ $("authKey").addEventListener("keydown", (e) => { if (e.key === "Enter") submitAuth() })
651
+
652
+ function fmtTime(val) {
653
+ if (!val) return "–"
654
+ return String(val)
655
+ }
656
+ function fmtLogTime(val) {
657
+ if (!val) return ""
658
+ return String(val)
659
+ }
660
+ function fmtDur(ms) { return ms < 1000 ? ms + "ms" : (ms / 1000).toFixed(1) + "s" }
661
+ function fmtUp(sec) {
662
+ const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60
663
+ return h > 0 ? h + "h " + m + "m" : m > 0 ? m + "m " + s + "s" : s + "s"
664
+ }
665
+
666
+ async function refreshStatus() {
667
+ try {
668
+ const st = await api("/api/status")
669
+ const dot = $("upstreamDot"), txt = $("upstreamText")
670
+ dot.className = "dot " + (st.upstreamOk ? "ok" : "bad")
671
+ txt.textContent = st.upstreamOk ? "upstream OK" : "upstream DOWN"
672
+ $("ovUpstream").textContent = st.upstream.replace(/^https?:\/\//, "")
673
+ $("ovUpstream").title = st.upstream
674
+ $("ovUpstream").dataset.host = new URL(st.upstream).host || st.upstream
675
+ $("ovUa").textContent = "UA: " + st.ua
676
+ $("ovUa").title = st.uaAutoVersion && st.uaAutoVersion !== (st.ua.split("/")[1] || "") ? "latest opencode: " + st.uaAutoVersion : ""
677
+ $("ovUptime").textContent = fmtUp(st.uptime)
678
+ $("ovTotal").textContent = st.requests.total
679
+ $("ovErr").textContent = st.requests.errors + " errors"
680
+ $("ovMin").textContent = st.requests.lastMinute
681
+ $("ov5m").textContent = st.requests.last5m + " in 5 min"
682
+ $("ovModels").textContent = st.models.total
683
+ $("ovAllowed").textContent = st.models.allowed + " allowed"
684
+ if (document.getElementById("tab-overview").classList.contains("active")) renderTable(st.recent)
685
+ if (document.getElementById("tab-models").classList.contains("active")) {
686
+ if (!config) {
687
+ const c = await api("/api/config").catch(() => null)
688
+ if (c && c.config) config = c.config
689
+ }
690
+ renderModels(st)
691
+ }
692
+ hideBanner()
693
+ } catch (e) {
694
+ if (e.message !== "unauthorized") { $("upstreamDot").className = "dot bad"; $("upstreamText").textContent = "unreachable" }
695
+ }
696
+ }
697
+
698
+ const PAGE_SIZE = 10
699
+ let tablePage = 1
700
+ function renderTable(recent) {
701
+ const tb = $("reqTable").querySelector("tbody")
702
+ const pager = $("reqPager")
703
+ if (!recent || !recent.length) {
704
+ tb.innerHTML = '<tr><td colspan="5" class="empty">no requests yet — go make some noise.</td></tr>'
705
+ pager.innerHTML = ""
706
+ return
707
+ }
708
+ const rows = recent.slice()
709
+ const pages = Math.max(1, Math.ceil(rows.length / PAGE_SIZE))
710
+ if (tablePage > pages) tablePage = pages
711
+ if (tablePage < 1) tablePage = 1
712
+ const slice = rows.slice((tablePage - 1) * PAGE_SIZE, tablePage * PAGE_SIZE)
713
+ tb.innerHTML = slice.map((r) => {
714
+ const cls = r.status < 300 ? "ok" : r.status === 429 ? "warn" : "bad"
715
+ const t = r.at || r.time
716
+ return `<tr>
717
+ <td class="mono">${fmtTime(t)}</td>
718
+ <td class="mono">${escapeHtml(r.model)}</td>
719
+ <td><span class="badge ${cls}">${r.status}</span></td>
720
+ <td class="mono">${r.ms == null ? "—" : fmtDur(r.ms)}</td>
721
+ <td class="mono">${r.count || 1}</td>
722
+ </tr>`
723
+ }).join("")
724
+ pager.innerHTML = `
725
+ <button onclick="pageTable(-1)" ${tablePage <= 1 ? "disabled" : ""}>‹ prev</button>
726
+ <span class="pager-info">page ${tablePage} / ${pages} · ${rows.length} entries</span>
727
+ <button onclick="pageTable(1)" ${tablePage >= pages ? "disabled" : ""}>next ›</button>`
728
+ }
729
+ function pageTable(d) { tablePage += d; refreshStatus() }
730
+
731
+ async function refreshModels() {
732
+ try {
733
+ const cfg = await api("/api/config")
734
+ if (cfg && cfg.config) config = cfg.config
735
+ } catch {}
736
+ const st = await api("/api/status")
737
+ renderModels(st)
738
+ }
739
+
740
+ function renderModels(st) {
741
+ const tb = $("modelTable").querySelector("tbody")
742
+ const fb = (config && Array.isArray(config.fallbackModels)) ? config.fallbackModels : []
743
+ const disabled = (config && Array.isArray(config.disabledModels)) ? config.disabledModels : []
744
+ const aliases = (config && typeof config.modelAliases === "object" && config.modelAliases !== null) ? config.modelAliases : {}
745
+ const servedIds = ((st && st.models && Array.isArray(st.models.served)) ? st.models.served : []).map((m) => (typeof m === "string" ? m : m.id))
746
+ const discoveredIds = ((st && st.models && Array.isArray(st.models.discovered)) ? st.models.discovered : []).map((m) => (typeof m === "string" ? m : m.id))
747
+ const dead = (st && st.sync && Array.isArray(st.sync.dead)) ? st.sync.dead : []
748
+ // Only show models that exist upstream (discovered/served), or are in fallback/aliases, or are explicitly disabled
749
+ const upstreamOrConfigured = new Set([...fb, ...servedIds, ...discoveredIds, ...Object.keys(aliases)])
750
+ const allKnown = [...new Set([...fb, ...disabled, ...servedIds, ...discoveredIds, ...Object.keys(aliases)])]
751
+ // Filter out dead upstream models, AND filter out custom models that are not upstream and not in fb/aliases
752
+ const list = allKnown.filter((m) => {
753
+ if (dead.includes(m) && !fb.includes(m) && !aliases[m]) return false
754
+ return true
755
+ })
756
+ const unconfigured = allKnown.filter((m) => !fb.includes(m) && !aliases[m])
757
+ $("modelCount").textContent = list.length + " available" + (unconfigured.length ? ` · ${unconfigured.length} not in fallback` : "")
758
+ if (st && st.sync) renderSync(st.sync)
759
+ if (!list.length) { tb.innerHTML = '<tr><td colspan="4" class="empty">no models available right now.</td></tr>'; return }
760
+ tb.innerHTML = list.map((m) => {
761
+ const sync = st && st.sync
762
+ const aliasTarget = aliases[m]
763
+ const ms = modelStatus(aliasTarget || m, sync)
764
+ const display = aliasTarget ? escapeHtml(m) + ' <span class="badge mut">→ ' + escapeHtml(aliasTarget) + "</span>" : escapeHtml(m)
765
+ const msBadge = ms ? `<span class="badge ${ms.cls}" style="margin-left:7px" tabindex="0" data-tip-title="${escapeAttr(ms.title || ms.label)}" data-tip="${escapeAttr(ms.tip)}">${ms.label}</span>` : ""
766
+ const isResp = ((config && config.responsesModels) || []).some((p) => (p.endsWith("*") ? m.startsWith(p.slice(0, -1)) : m === p))
767
+ const fmtBadge = isResp ? `<span class="badge mut" style="margin-left:6px" tabindex="0" data-tip="${escapeAttr(TIP.responses)}">responses</span>` : ""
768
+ const isDefault = m === (config && config.defaultModel)
769
+ const isConfigured = fb.includes(m) || !!aliases[m]
770
+ const isDisabled = disabled.includes(m)
771
+ const notInFallback = !fb.includes(m) && !aliases[m]
772
+ const notCfgBadge = isDisabled ? `<span class="badge warn" style="margin-left:6px" tabindex="0" title="Model disabled by user">disabled</span>` : (notInFallback ? `<span class="badge mut" style="margin-left:6px" tabindex="0" data-tip="${escapeAttr(TIP.notconfigured)}">not in fallback</span>` : "")
773
+ const addBtn = notInFallback ? `<button onclick='addModel(${jsStr(m)})'>+ enable</button>` : ""
774
+ return `<tr${notInFallback ? ' style="opacity:.7"' : ""}>
775
+ <td class="mono" style="vertical-align:middle;padding:12px 10px">
776
+ <div style="display:inline-flex;align-items:center;flex-wrap:wrap;gap:6px;row-gap:4px">
777
+ <span style="font-weight:700;letter-spacing:-.01em">${display}</span>
778
+ ${msBadge}
779
+ ${fmtBadge}
780
+ ${notCfgBadge}
781
+ </div>
782
+ </td>
783
+ <td style="vertical-align:middle;text-align:center;padding:12px 6px">
784
+ <input type="radio" name="defaultModel" value="${escapeAttr(m)}" ${isDefault ? "checked" : ""} onchange='setDefault(${jsStr(m)})' style="width:16px;height:16px;cursor:pointer;margin:0 auto;display:block">
785
+ </td>
786
+ <td class="mono testCell" id="tc-${escapeAttr(m)}" style="vertical-align:middle;padding:12px 10px">
787
+ ${(() => {
788
+ const mt = manualTests[m] || (aliasTarget && manualTests[aliasTarget])
789
+ if (mt) {
790
+ if (mt.gated) {
791
+ return `<span class="badge mut" tabindex="0" data-tip="${escapeAttr(TIP.gated)}">◦ agent-only</span>`
792
+ }
793
+ const okColor = mt.ok ? "var(--ink)" : "var(--coral)"
794
+ const detailHtml = mt.detail ? `<div class="hint" style="font-size:10px;line-height:1.25;margin-top:3px;word-break:break-word;max-width:280px;font-family:var(--mono);color:var(--muted)" title="${escapeAttr(String(mt.detail))}">${escapeHtml(String(mt.detail))}</div>` : ""
795
+ return `<div><span style="color:${okColor};font-weight:700;font-size:11px">${mt.ok ? "✓" : "✗"} ${mt.status} · ${fmtDur(mt.ms)}</span>${detailHtml}</div>`
796
+ }
797
+ const targetKey = aliasTarget || m
798
+ const isWorkingInSync = st && st.sync && Array.isArray(st.sync.working) && (st.sync.working.includes(targetKey) || st.sync.working.includes(m))
799
+ const obs = (st && st.sync && st.sync.observed && (st.sync.observed[targetKey] || st.sync.observed[m]))
800
+ if (obs && (obs.ok > 0 || obs.fail > 0)) {
801
+ const ok = obs.ok > 0 || (isWorkingInSync && obs.fail === 0)
802
+ if (obs.ok > 0) {
803
+ return `<span class="badge ${obs.ok >= obs.fail ? "ok" : "bad"}" style="font-size:10px">${obs.ok >= obs.fail ? "✓ " + obs.ok + " ok" : "✗ " + obs.fail + " fail"}</span>`
804
+ }
805
+ }
806
+ if (isWorkingInSync) {
807
+ return `<span class="badge ok" style="font-size:10px">✓ ready</span>`
808
+ }
809
+ if (obs && obs.fail > 0) {
810
+ return `<span class="badge bad" style="font-size:10px">✗ ${obs.fail} fail</span>`
811
+ }
812
+ if (st && st.sync && Array.isArray(st.sync.flaky) && (st.sync.flaky.includes(targetKey) || st.sync.flaky.includes(m))) {
813
+ return `<span class="badge warn" style="font-size:10px">~ flaky</span>`
814
+ }
815
+ if (st && st.sync && Array.isArray(st.sync.dead) && (st.sync.dead.includes(targetKey) || st.sync.dead.includes(m))) {
816
+ return `<span class="badge bad" style="font-size:10px">✗ dead</span>`
817
+ }
818
+ return `<span style="color:var(--muted)">–</span>`
819
+ })()}
820
+ </td>
821
+ <td style="vertical-align:middle;text-align:right;padding:12px 16px 12px 6px">
822
+ <div style="display:inline-flex;align-items:center;justify-content:flex-end;gap:6px;white-space:nowrap">
823
+ <button style="padding:5px 11px;font-size:10px;min-width:48px" onclick='testModel(${jsStr(m)})'>Test</button>
824
+ ${(() => {
825
+ if (aliasTarget) {
826
+ return `<button style="padding:5px 8px;font-size:10px;background:rgba(235,94,85,.15);color:var(--coral);border:1px solid rgba(235,94,85,.3)" title="Delete alias completely" onclick='deleteAlias(${jsStr(m)})'>✕</button>`
827
+ }
828
+ if (isDisabled) {
829
+ return `<button style="padding:5px 9px;font-size:10px" onclick='addModel(${jsStr(m)})'>+ enable</button><button style="padding:5px 8px;font-size:10px;background:rgba(235,94,85,.15);color:var(--coral);border:1px solid rgba(235,94,85,.3)" title="Delete model completely" onclick='deleteModel(${jsStr(m)})'>✕</button>`
830
+ }
831
+ if (notInFallback) {
832
+ return `<button style="padding:5px 9px;font-size:10px" onclick='addModel(${jsStr(m)})'>+ add</button>`
833
+ }
834
+ return `<button style="padding:5px 8px;font-size:10px;background:var(--paper2);color:var(--ink)" title="Disable model" onclick='removeModel(${jsStr(m)})'>✕</button>`
835
+ })()}
836
+ </div>
837
+ </td>
838
+ </tr>`
839
+ }).join("")
840
+ if (st && st.models) $("ovModels").textContent = st.models.total || list.length
841
+ }
842
+
843
+ async function setDefault(m) {
844
+ const cfg = await api("/api/config")
845
+ cfg.config.defaultModel = m
846
+ await api("/api/config", { method: "PUT", body: JSON.stringify(cfg.config) })
847
+ toast("Default model: " + m)
848
+ refreshModels()
849
+ }
850
+
851
+ async function testModel(m) {
852
+ const cell = $("tc-" + m)
853
+ if (cell) cell.innerHTML = `<span class="badge warn" style="font-size:10px">testing…</span>`
854
+ try {
855
+ const r = await api("/api/test", { method: "POST", body: JSON.stringify({ model: m }) })
856
+ manualTests[m] = { ...r, at: Date.now() }
857
+ if (cell) {
858
+ if (r.gated) {
859
+ cell.innerHTML = `<span class="badge mut" tabindex="0" data-tip="${escapeAttr(TIP.gated)}">◦ agent-only</span> <span class="hint">agent-only</span>`
860
+ } else {
861
+ const okColor = r.ok ? "var(--ink)" : "var(--coral)"
862
+ const detailHtml = r.detail ? `<div class="hint" style="font-size:10px;line-height:1.25;margin-top:3px;word-break:break-word;max-width:280px;font-family:var(--mono);color:var(--muted)" title="${escapeAttr(String(r.detail))}">${escapeHtml(String(r.detail))}</div>` : ""
863
+ cell.innerHTML = `<div><span style="color:${okColor};font-weight:700;font-size:11px">${r.ok ? "✓" : "✗"} ${r.status} · ${fmtDur(r.ms)}</span>${detailHtml}</div>`
864
+ }
865
+ }
866
+ toast(r.ok ? m + " works (" + r.status + " · " + fmtDur(r.ms) + ")" : m + " failed (" + r.status + ")", r.ok ? "ok" : "bad")
867
+ } catch {
868
+ if (cell) cell.innerHTML = `<span class="badge bad" style="font-size:10px">error</span>`
869
+ }
870
+ }
871
+
872
+ // Tooltip copy for each health state — kept short so it always fits the bubble.
873
+ const TIP = {
874
+ live: "A real request through this proxy just succeeded.",
875
+ ok: "Health probe got a clean 200 upstream.",
876
+ gated: "Free tier takes real agent traffic only. A probe can't confirm it.",
877
+ flaky: "Temporary trouble — timeout or 5xx. Kept, it recovers.",
878
+ limited: "Upstream returned 429. Quota refills.",
879
+ dead: "Upstream says it's gone (404). Only state that removes it.",
880
+ untested: "No health check yet. Hit “Sync now”.",
881
+ responses: "Served on /v1/responses. Proxy translates it.",
882
+ notconfigured: "Upstream has it, your list doesn't.",
883
+ syncing: "Probing every free model right now.",
884
+ syncnever: "Auto-sync has not run yet.",
885
+ syncdone: "Last health check. Agent-only models are fine — a probe just can't confirm them.",
886
+ }
887
+
888
+ function modelStatus(m, sync) {
889
+ if (sync && sync.observed && sync.observed[m]) {
890
+ const o = sync.observed[m]
891
+ if (o.ok > o.fail) return { cls: "ok", label: "ok (live traffic)", title: "live traffic", tip: TIP.live }
892
+ }
893
+ if (!sync || !sync.at) return { cls: "mut", label: "untested", tip: TIP.untested }
894
+ if (sync.working?.includes(m)) return { cls: "ok", label: "ok", tip: TIP.ok }
895
+ if (sync.rateLimited?.includes(m)) return { cls: "warn", label: "rate-limited", tip: TIP.limited }
896
+ if (sync.gated?.includes(m)) return { cls: "mut", label: "agent-only", tip: TIP.gated }
897
+ if (sync.flaky?.includes(m)) return { cls: "warn", label: "flaky", tip: TIP.flaky }
898
+ if (sync.dead?.includes(m)) return { cls: "bad", label: "dead", tip: TIP.dead }
899
+ return { cls: "mut", label: "untested", tip: TIP.untested }
900
+ }
901
+
902
+ function renderSync(s) {
903
+ const el = $("syncStatus")
904
+ if (!el) return
905
+ // The label itself is long, so the tooltip always uses a short fixed title.
906
+ el.setAttribute("data-tip-title", "auto-sync")
907
+ el.setAttribute("tabindex", "0")
908
+ if (s.running) { el.textContent = "auto-sync: probing…"; el.className = "badge warn"; el.setAttribute("data-tip", TIP.syncing); return }
909
+ if (!s.at) { el.textContent = "sync: never"; el.className = "badge mut"; el.setAttribute("data-tip", TIP.syncnever); return }
910
+ const ago = fmtUp(Math.max(1, Math.floor((Date.now() - s.at) / 1000))) + " ago"
911
+ const workingLen = (s.working || []).length
912
+ const rateLen = (s.rateLimited || []).length
913
+ const gatedLen = (s.gated || []).length
914
+ const flakyLen = (s.flaky || []).length
915
+ const deadLen = (s.dead || []).length
916
+ el.textContent = `sync: ${ago} · ${workingLen} ok · ${rateLen} rate-limited · ${gatedLen} agent-only · ${flakyLen} flaky · ${deadLen} dead`
917
+ el.className = "badge " + (s.ok ? (deadLen ? "warn" : "ok") : "bad")
918
+ let tipDetails = TIP.syncdone
919
+ if (deadLen) tipDetails += "\n\nDead: " + s.dead.join(", ")
920
+ if (flakyLen) tipDetails += "\n\nFlaky: " + s.flaky.join(", ")
921
+ el.setAttribute("data-tip", tipDetails)
922
+ }
923
+
924
+ async function syncNow() {
925
+ const btn = $("syncBtn")
926
+ btn.disabled = true
927
+ btn.textContent = "syncing…"
928
+ try {
929
+ const r = await api("/api/sync", { method: "POST" })
930
+ toast(r.ok ? "Sync started — probing models…" : "Sync failed: " + (r.error || ""), r.ok ? "ok" : "bad")
931
+ } catch { toast("Sync failed", "bad") }
932
+ // Poll until sync probe completes so the UI updates live
933
+ const poll = async () => {
934
+ await refreshModels()
935
+ const st = await api("/api/status").catch(() => null)
936
+ if (st && st.sync && st.sync.running) {
937
+ setTimeout(poll, 1000)
938
+ } else {
939
+ btn.disabled = false
940
+ btn.textContent = "⟳ Sync now"
941
+ await refreshModels()
942
+ }
943
+ }
944
+ setTimeout(poll, 1000)
945
+ }
946
+
947
+ async function testUpstreamKey() {
948
+ const hint = $("upstreamKeyHint")
949
+ hint.textContent = "testing…"
950
+ const upstreamKey = $("cfgUpstreamKey").value
951
+ const body = { model: $("cfgDefault").value.trim() || (config && config.fallbackModels ? config.fallbackModels[0] : "") }
952
+ if (upstreamKey && upstreamKey !== savedUpstreamKeyMasked) body.upstreamKey = upstreamKey
953
+ try {
954
+ const r = await api("/api/test", { method: "POST", body: JSON.stringify(body) })
955
+ if (r.gated) {
956
+ hint.innerHTML = '<span style="color:var(--mut)">◦ key accepted, model is agent-only</span>'
957
+ toast("Key reached the free tier (model is agent-only)", "ok")
958
+ } else {
959
+ hint.innerHTML = r.ok
960
+ ? '<span style="color:var(--ink)">✓ works (' + r.model + ")</span>"
961
+ : '<span style="color:var(--coral)">✗ ' + r.status + " " + escapeHtml(String(r.detail || "").slice(0, 80)) + "</span>"
962
+ toast(r.ok ? "Key works: " + r.model : "Key rejected (" + r.status + ")", r.ok ? "ok" : "bad")
963
+ }
964
+ } catch (e) { hint.textContent = "test failed"; toast("Test failed", "bad") }
965
+ }
966
+
967
+ async function addModel(preset) {
968
+ const m = (preset || $("newModel").value).trim()
969
+ if (!m) return
970
+ const cfg = await api("/api/config")
971
+ if (!Array.isArray(cfg.config.fallbackModels)) cfg.config.fallbackModels = []
972
+ if (Array.isArray(cfg.config.disabledModels)) {
973
+ cfg.config.disabledModels = cfg.config.disabledModels.filter((x) => x !== m)
974
+ }
975
+ if (!cfg.config.fallbackModels.includes(m)) cfg.config.fallbackModels.push(m)
976
+ await api("/api/config", { method: "PUT", body: JSON.stringify(cfg.config) })
977
+ $("newModel").value = ""
978
+ toast("Enabled " + m)
979
+ refreshModels()
980
+ }
981
+
982
+ async function removeModel(m) {
983
+ const cfg = await api("/api/config")
984
+ if (!Array.isArray(cfg.config.disabledModels)) cfg.config.disabledModels = []
985
+ if (!cfg.config.disabledModels.includes(m)) cfg.config.disabledModels.push(m)
986
+ cfg.config.fallbackModels = cfg.config.fallbackModels.filter((x) => x !== m)
987
+ if (cfg.config.defaultModel === m) cfg.config.defaultModel = cfg.config.fallbackModels[0] || ""
988
+ await api("/api/config", { method: "PUT", body: JSON.stringify(cfg.config) })
989
+ toast("Disabled " + m)
990
+ refreshModels()
991
+ }
992
+
993
+ async function deleteModel(m) {
994
+ const cfg = await api("/api/config")
995
+ if (Array.isArray(cfg.config.disabledModels)) {
996
+ cfg.config.disabledModels = cfg.config.disabledModels.filter((x) => x !== m)
997
+ }
998
+ if (Array.isArray(cfg.config.fallbackModels)) {
999
+ cfg.config.fallbackModels = cfg.config.fallbackModels.filter((x) => x !== m)
1000
+ }
1001
+ if (cfg.config.modelAliases && cfg.config.modelAliases[m]) {
1002
+ delete cfg.config.modelAliases[m]
1003
+ }
1004
+ if (cfg.config.defaultModel === m) cfg.config.defaultModel = cfg.config.fallbackModels[0] || ""
1005
+ await api("/api/config", { method: "PUT", body: JSON.stringify(cfg.config) })
1006
+ toast("Deleted " + m, "ok")
1007
+ refreshModels()
1008
+ }
1009
+
1010
+ async function deleteAlias(m) {
1011
+ const cfg = await api("/api/config")
1012
+ if (cfg.config.modelAliases && cfg.config.modelAliases[m]) {
1013
+ delete cfg.config.modelAliases[m]
1014
+ }
1015
+ await api("/api/config", { method: "PUT", body: JSON.stringify(cfg.config) })
1016
+ toast("Removed alias " + m, "ok")
1017
+ refreshModels()
1018
+ }
1019
+
1020
+ async function populateConfigForm() {
1021
+ if (!config) config = (await api("/api/config")).config
1022
+ savedUpstreamKeyMasked = config.defaultUpstreamKey || ""
1023
+ $("cfgHost").value = config.host
1024
+ $("cfgPort").value = config.port
1025
+ $("cfgUpstream").value = config.upstream
1026
+ $("cfgOutboundProxy").value = config.outboundProxy || ""
1027
+ $("cfgUa").value = config.ua
1028
+ $("cfgDefault").value = config.defaultModel
1029
+ $("cfgDefault").placeholder = "(auto)"
1030
+ $("cfgProxyKey").value = config.proxyKey === "••••••••" ? "" : config.proxyKey
1031
+ $("cfgUpstreamKey").value = savedUpstreamKeyMasked
1032
+ $("cfgTimeout").value = config.timeoutMs
1033
+ $("cfgFallback").value = JSON.stringify(config.fallbackModels, null, 2)
1034
+ $("cfgAliases").value = JSON.stringify(config.modelAliases, null, 2)
1035
+ $("cfgTrust").checked = !!config.trustForwarded
1036
+ $("cfgAutoSync").checked = config.autoSync !== false
1037
+ $("cfgSyncMs").value = config.autoSyncIntervalMs ?? 3600000
1038
+ $("cfgMetaEndpoint").value = config.metaEndpoint || "https://models.dev/api.json"
1039
+ $("cfgMetaTimeout").value = config.metaTimeoutSec || 30
1040
+ $("cfgMetaSyncHours").value = config.metaSyncHours || 24
1041
+ $("cfgProbeAuth").value = ["auto", "key", "anonymous"].includes(config.probeAuth) ? config.probeAuth : "auto"
1042
+ $("cfgAutoUA").checked = config.autoUA !== false
1043
+ $("cfgUaDays").value = config.uaRefreshDays != null ? config.uaRefreshDays : (config.uaRefreshMs ? +(config.uaRefreshMs / 86400000).toFixed(2) : 1)
1044
+ $("cfgInject").checked = config.injectSession !== false
1045
+ $("cfgRateLimit").checked = Number(config.rateLimitMax) > 0
1046
+ $("cfgRateMax").value = config.rateLimitMax ?? 0
1047
+ $("cfgRateWindow").value = config.rateLimitWindowMs ?? 60000
1048
+ $("cfgResponses").value = JSON.stringify(config.responsesModels ?? [], null, 2)
1049
+ try {
1050
+ const st = await api("/api/status")
1051
+ const auth = st.auth || {}
1052
+ const modeLabel =
1053
+ auth.mode === "proxy+byok" ? "proxy key + your upstream key"
1054
+ : auth.mode === "byok" ? "your upstream key"
1055
+ : auth.mode === "proxy" ? "proxy key"
1056
+ : "anonymous public"
1057
+ const eff = st.effectiveDefault ? " · auto→" + st.effectiveDefault : ""
1058
+ $("cfgDefault").placeholder = eff ? "auto → " + st.effectiveDefault : "(auto)"
1059
+ $("cfgAuth").textContent = "auth: " + modeLabel + (auth.upstreamKey ? " (" + auth.upstreamKey + ")" : "") + eff
1060
+ } catch {}
1061
+ }
1062
+
1063
+ async function saveConfig() {
1064
+ const body = {
1065
+ host: $("cfgHost").value.trim() || "127.0.0.1",
1066
+ port: Number($("cfgPort").value || 8787),
1067
+ upstream: $("cfgUpstream").value.trim(),
1068
+ outboundProxy: $("cfgOutboundProxy").value.trim(),
1069
+ ua: $("cfgUa").value.trim(),
1070
+ defaultModel: $("cfgDefault").value.trim(),
1071
+ proxyKey: $("cfgProxyKey").value,
1072
+ timeoutMs: Number($("cfgTimeout").value || 120000),
1073
+ fallbackModels: JSON.parse($("cfgFallback").value || "[]"),
1074
+ modelAliases: JSON.parse($("cfgAliases").value || "{}"),
1075
+ trustForwarded: $("cfgTrust").checked,
1076
+ autoSync: $("cfgAutoSync").checked,
1077
+ autoSyncIntervalMs: Number($("cfgSyncMs").value || 3600000),
1078
+ metaEndpoint: $("cfgMetaEndpoint").value.trim() || "https://models.dev/api.json",
1079
+ metaTimeoutSec: Number($("cfgMetaTimeout").value || 30),
1080
+ metaSyncHours: Number($("cfgMetaSyncHours").value || 24),
1081
+ probeAuth: $("cfgProbeAuth").value,
1082
+ autoUA: $("cfgAutoUA").checked,
1083
+ uaRefreshDays: Number($("cfgUaDays").value || 1),
1084
+ uaRefreshMs: Math.round(Number($("cfgUaDays").value || 1) * 86400000),
1085
+ injectSession: $("cfgInject").checked,
1086
+ rateLimitMax: $("cfgRateLimit").checked ? Number($("cfgRateMax").value || 0) : 0,
1087
+ rateLimitWindowMs: Number($("cfgRateWindow").value || 60000),
1088
+ }
1089
+ try { body.responsesModels = JSON.parse($("cfgResponses").value || "[]") } catch { toast("Invalid JSON — responses models", "bad"); return }
1090
+ if ($("cfgUpstreamKey").value !== savedUpstreamKeyMasked) body.defaultUpstreamKey = $("cfgUpstreamKey").value
1091
+ try {
1092
+ const r = await api("/api/config", { method: "PUT", body: JSON.stringify(body) })
1093
+ if (r && r.config) {
1094
+ config = r.config
1095
+ savedUpstreamKeyMasked = config.defaultUpstreamKey || ""
1096
+ }
1097
+ toast("Saved & applied", "ok")
1098
+ await refreshModels()
1099
+ await refreshStatus()
1100
+ } catch (e) { toast("Failed to save config: " + (e.message || "check JSON"), "bad") }
1101
+ }
1102
+
1103
+ async function restoreModels() {
1104
+ try {
1105
+ const r = await api("/api/config", { method: "POST", body: JSON.stringify({ fallbackModels: true }) })
1106
+ config = r.config
1107
+ toast("Model list restored (" + config.fallbackModels.length + " models) — syncing now")
1108
+ await api("/api/sync", { method: "POST" })
1109
+ refreshAll()
1110
+ } catch { toast("Restore failed", "bad") }
1111
+ }
1112
+
1113
+ async function reloadConfig() { config = null; await populateConfigForm(); toast("Reloaded from file") }
1114
+
1115
+ function resetStats() {
1116
+ if (!confirm("Are you sure you want to clear request history and stats?")) return
1117
+ try {
1118
+ api("/api/reset", { method: "POST" }).then(() => {
1119
+ manualTests = {}
1120
+ toast("Stats cleared", "ok")
1121
+ refreshStatus()
1122
+ refreshModels()
1123
+ })
1124
+ } catch (e) {
1125
+ toast("Failed to reset stats", "bad")
1126
+ }
1127
+ }
1128
+
1129
+ async function loadLogs() {
1130
+ if (!document.getElementById("tab-logs").classList.contains("active")) return
1131
+ try {
1132
+ const r = await api("/api/logs?n=300")
1133
+ const box = $("logBox")
1134
+ box.innerHTML = r.logs.map((l) => `<div class="line"><span class="ts">${escapeHtml(fmtLogTime(l.at))}</span>${escapeHtml(l.msg)}</div>`).join("") || '<div class="empty">No logs</div>'
1135
+ box.scrollTop = box.scrollHeight
1136
+ } catch {}
1137
+ }
1138
+
1139
+ function positionIndicator() {
1140
+ const nav = $("nav"), ind = $("navIndicator")
1141
+ const act = nav.querySelector("button.active")
1142
+ if (!act) return
1143
+ ind.style.width = act.offsetWidth + "px"
1144
+ ind.style.transform = `translateX(${act.offsetLeft}px)`
1145
+ }
1146
+ window.addEventListener("resize", positionIndicator)
1147
+
1148
+ function switchTab(name) {
1149
+ document.querySelectorAll("nav button").forEach((b) => b.classList.toggle("active", b.dataset.tab === name))
1150
+ document.querySelectorAll(".tab").forEach((t) => {
1151
+ const is = t.id === "tab-" + name
1152
+ if (is) {
1153
+ t.classList.remove("leaving")
1154
+ t.classList.add("active")
1155
+ } else if (t.classList.contains("active")) {
1156
+ t.classList.remove("active")
1157
+ t.classList.add("leaving")
1158
+ setTimeout(() => t.classList.remove("leaving"), 340)
1159
+ }
1160
+ })
1161
+ positionIndicator()
1162
+ if (name === "config") populateConfigForm()
1163
+ if (name === "logs") loadLogs()
1164
+ if (name === "models") { config = null; refreshModels() }
1165
+ if (name === "overview") refreshStatus()
1166
+ }
1167
+ document.querySelectorAll("nav button").forEach((b) => b.addEventListener("click", () => switchTab(b.dataset.tab)))
1168
+
1169
+ function escapeHtml(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c])) }
1170
+
1171
+ // --- badge tooltip (delegated, so it survives the 4s table re-render) ---
1172
+ // Purpose-built for this dashboard. One accent per badge tone, tuned dark
1173
+ // enough to read on the paper background. Title reuses the badge's own label
1174
+ // so the two never drift apart.
1175
+ const ZTIP_TONE = { ok: "#4d6b00", warn: "#6b3fbf", bad: "#d63a1c", mut: "#7d7461" }
1176
+ let ztipEl = null
1177
+ function ztipHide() {
1178
+ if (!ztipEl) return
1179
+ const el = ztipEl
1180
+ ztipEl = null
1181
+ el.classList.remove("open")
1182
+ setTimeout(() => el.remove(), 220)
1183
+ }
1184
+ function ztipShow(target) {
1185
+ const body = target.getAttribute("data-tip")
1186
+ if (!body) return
1187
+ ztipHide()
1188
+ const tone = (target.className.match(/badge\s+(\w+)/) || [])[1] || "mut"
1189
+ const bubble = document.createElement("div")
1190
+ bubble.className = "ztip"
1191
+ bubble.setAttribute("role", "tooltip")
1192
+ bubble.style.setProperty("--ztip-accent", ZTIP_TONE[tone] || ZTIP_TONE.mut)
1193
+ const title = document.createElement("div")
1194
+ title.className = "ztip-title"
1195
+ title.textContent = target.getAttribute("data-tip-title") || target.textContent.trim()
1196
+ const text = document.createElement("div")
1197
+ text.className = "ztip-body"
1198
+ text.textContent = body
1199
+ bubble.append(title, text)
1200
+ target.appendChild(bubble)
1201
+ ztipEl = bubble
1202
+ // Flip below when there is not enough room above, then keep it on screen.
1203
+ if (target.getBoundingClientRect().top < 150) bubble.classList.add("below")
1204
+ const half = bubble.offsetWidth / 2
1205
+ const r = target.getBoundingClientRect()
1206
+ const shift = Math.round(r.left + r.width / 2 - (bubble.getBoundingClientRect().left + half))
1207
+ if (shift) bubble.style.marginLeft = shift + "px"
1208
+ requestAnimationFrame(() => bubble.classList.add("open"))
1209
+ }
1210
+ document.addEventListener("mouseover", (e) => {
1211
+ const t = e.target.closest && e.target.closest("[data-tip]")
1212
+ if (t) ztipShow(t)
1213
+ })
1214
+ document.addEventListener("mouseout", (e) => {
1215
+ const t = e.target.closest && e.target.closest("[data-tip]")
1216
+ if (t && (!e.relatedTarget || !t.contains(e.relatedTarget))) ztipHide()
1217
+ })
1218
+ document.addEventListener("focusin", (e) => {
1219
+ const t = e.target.closest && e.target.closest("[data-tip]")
1220
+ if (t) ztipShow(t)
1221
+ })
1222
+ document.addEventListener("focusout", ztipHide)
1223
+ window.addEventListener("scroll", ztipHide, true)
1224
+ window.addEventListener("resize", ztipHide)
1225
+
1226
+ function escapeAttr(s) { return escapeHtml(s) }
1227
+ // Safe embedding of a JS string into a single-quoted HTML attribute: HTML attribute
1228
+ // parsing does not honor \" as an escape, so JSON.stringify alone breaks double-quoted
1229
+ // attributes; \x27 and \u0026 survive attribute parsing and decode inside the JS string.
1230
+ function jsStr(s) {
1231
+ return JSON.stringify(String(s ?? "")).replace(/'/g, "\\x27").replace(/&/g, "\\u0026")
1232
+ }
1233
+
1234
+ function updateEndpointBanner() {
1235
+ const el = $("endpointUrl")
1236
+ if (el) el.textContent = window.location.origin + "/v1"
1237
+ }
1238
+ function copyEndpoint() {
1239
+ const url = window.location.origin + "/v1"
1240
+ const btn = $("copyBtn")
1241
+ const setCopied = () => {
1242
+ if (btn) {
1243
+ const origText = btn.textContent
1244
+ btn.textContent = "✓ Copied!"
1245
+ btn.style.background = "#10b981"
1246
+ btn.style.borderColor = "#10b981"
1247
+ setTimeout(() => {
1248
+ btn.textContent = origText
1249
+ btn.style.background = ""
1250
+ btn.style.borderColor = ""
1251
+ }, 2000)
1252
+ }
1253
+ toast("Copied URL: " + url, "ok")
1254
+ }
1255
+
1256
+ // 1. Try modern clipboard API
1257
+ if (navigator.clipboard && window.isSecureContext) {
1258
+ navigator.clipboard.writeText(url).then(setCopied).catch(() => fallbackCopy(url, setCopied))
1259
+ } else {
1260
+ // 2. HTTP / non-secure context fallback (textarea execCommand)
1261
+ fallbackCopy(url, setCopied)
1262
+ }
1263
+ }
1264
+ function fallbackCopy(text, cb) {
1265
+ try {
1266
+ const ta = document.createElement("textarea")
1267
+ ta.value = text
1268
+ ta.style.position = "fixed"
1269
+ ta.style.top = "-9999px"
1270
+ ta.style.left = "-9999px"
1271
+ document.body.appendChild(ta)
1272
+ ta.focus()
1273
+ ta.select()
1274
+ const ok = document.execCommand("copy")
1275
+ document.body.removeChild(ta)
1276
+ if (ok) cb(); else toast(text, "ok")
1277
+ } catch {
1278
+ toast(text, "ok")
1279
+ }
1280
+ }
1281
+
1282
+ async function refreshAll() {
1283
+ updateEndpointBanner()
1284
+ try { await refreshStatus(); await refreshModels() } catch (e) { if (e.message === "unauthorized") showAuth() }
1285
+ }
1286
+
1287
+ if (key) {
1288
+ refreshAll()
1289
+ setTimeout(positionIndicator, 20)
1290
+ setInterval(refreshStatus, 4000)
1291
+ setInterval(loadLogs, 8000)
1292
+ } else {
1293
+ api("/api/status").then(() => {
1294
+ refreshAll()
1295
+ setTimeout(positionIndicator, 20)
1296
+ setInterval(refreshStatus, 4000)
1297
+ setInterval(loadLogs, 8000)
1298
+ }).catch(() => showAuth())
1299
+ }
1300
+ </script>
1301
+ </body>
1302
+ </html>
entrypoint.sh CHANGED
@@ -47,18 +47,61 @@ if [ ! -f /data/apps/opencode/opencode.json ]; then
47
  OPEOF
48
  fi
49
 
50
- # Clean clutter out of user /data/workspace
51
- rm -rf /data/workspace/.claude /data/workspace/.vscode /data/workspace/.opencode /data/workspace/config.yaml /data/workspace/hook-secret /data/workspace/session-lifecycle.jsonl /data/workspace/state.json* /data/workspace/subagent-window-states.json 2>/dev/null || true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Purge any code-server last-opened workspace memory so code-server opens blank with NO default folder
54
- rm -rf /data/apps/vscode/User/workspaceStorage /data/apps/vscode/User/History /data/apps/vscode/Backups 2>/dev/null || true
55
- mkdir -p /data/apps/vscode/User
56
- cat > /data/apps/vscode/User/settings.json << 'SETEOF'
57
- {
58
- "workbench.startupEditor": "none",
59
- "window.restoreWindows": "none"
60
- }
61
- SETEOF
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  # Clean legacy logs/tmp and active SQLite DBs from FUSE bucket to prevent deadlocks
64
  rm -rf /data/logs /data/tmp /data/.cache /data/openclaw /data/script/codeman /data/.hermes /data/.hermes-web-ui /data/.ekko-studio /data/.ekko 2>/dev/null || true
@@ -75,30 +118,38 @@ if [ -f /app/services/apps_sync.py ]; then
75
  nohup python3 /app/services/apps_sync.py > /tmp/logs/apps-sync.log 2>&1 &
76
  fi
77
 
 
 
 
 
 
 
 
 
 
 
 
78
  # Deploy clean opencode-router with assets and public UI into /data/script/opencode-router
79
  mkdir -p /data/script/opencode-router
80
  cp -rn /opt/opencode-router/* /data/script/opencode-router/ 2>/dev/null || true
81
  chmod +x /data/script/opencode-router/opencode-router 2>/dev/null || true
82
 
83
- # Copy clean index.html exactly from Hermes distribution with relative paths
84
- INDEX_HTML="/data/script/opencode-router/public/index.html"
85
- if [ -f "$INDEX_HTML" ]; then
86
- sed -i 's|const basePath = window.location.pathname.replace(/\\/+$/, "");||g' "$INDEX_HTML" 2>/dev/null || true
87
- sed -i 's|<head><base href="/opencode/">|<head>|g' "$INDEX_HTML" 2>/dev/null || true
88
- sed -i 's|href="/assets/|href="assets/|g' "$INDEX_HTML" 2>/dev/null || true
89
- sed -i 's|src="/assets/|src="assets/|g' "$INDEX_HTML" 2>/dev/null || true
90
- sed -i 's|function api(path,|const basePath = window.location.pathname.replace(/\\/+$/, ""); function api(path,|g' "$INDEX_HTML" 2>/dev/null || true
91
- sed -i 's|return fetch(path,|const targetPath = basePath + (path.startsWith("/") ? path : "/" + path); return fetch(targetPath,|g' "$INDEX_HTML" 2>/dev/null || true
92
  fi
93
 
94
- # Redirect caches & logs to /tmp so S3 doesn't accumulate garbage
95
- rm -rf /data/code-server/logs /data/code-server/CachedData /data/code-server/CachedExtensionVSIXs 2>/dev/null || true
96
- ln -sfn /tmp/logs /data/code-server/logs 2>/dev/null || true
97
- ln -sfn /tmp/code-server-cache /data/code-server/CachedData 2>/dev/null || true
98
-
99
- # Redirect Web UI logs to /tmp
100
- mkdir -p /data/.hermes-web-ui
101
- ln -sfn /tmp/logs /data/.hermes-web-ui/logs 2>/dev/null || true
102
 
103
  # 2. Persistent Caddyfile on /data (user-editable):
104
  # Always sync from template to apply latest routing rules and remove stale directives
 
47
  OPEOF
48
  fi
49
 
50
+ # Migrate Ekko/Hermes-Web-UI SQLite state out of the bucket. Older revisions ran the
51
+ # gateway with cwd=/data/workspace while NODE_ENV!=production, which made hermes-web-ui
52
+ # write to $CWD/packages/server/data/hermes-web-ui.db (S3 FUSE — never allowed there).
53
+ # Take whichever copy is newest, then drop the bucket-side tree. Must run BEFORE the
54
+ # workspace cleanup below and BEFORE apps_sync restore.
55
+ WS_EKKO_DB="/data/workspace/packages/server/data/hermes-web-ui.db"
56
+ LOCAL_EKKO_DB="/home/appuser/.hermes-web-ui/hermes-web-ui.db"
57
+ EKKO_DB_MIGRATED=1
58
+ mkdir -p /home/appuser/.hermes-web-ui
59
+ if [ -f "$WS_EKKO_DB" ]; then
60
+ if [ ! -f "$LOCAL_EKKO_DB" ] || [ "$WS_EKKO_DB" -nt "$LOCAL_EKKO_DB" ]; then
61
+ if cp -f "$WS_EKKO_DB" "$LOCAL_EKKO_DB" && [ -s "$LOCAL_EKKO_DB" ]; then
62
+ echo "📦 Migrated ekko state $WS_EKKO_DB -> $LOCAL_EKKO_DB ($(stat -c%s "$LOCAL_EKKO_DB") bytes)"
63
+ else
64
+ echo "⚠️ Failed to migrate $WS_EKKO_DB; leaving it in place for manual recovery"
65
+ EKKO_DB_MIGRATED=0
66
+ fi
67
+ fi
68
+ fi
69
 
70
+ # Clean clutter out of user /data/workspace (user files only — no app state, no SQLite)
71
+ rm -rf /data/workspace/.claude /data/workspace/.vscode /data/workspace/.opencode \
72
+ /data/workspace/config.yaml /data/workspace/hook-secret \
73
+ /data/workspace/session-lifecycle.jsonl /data/workspace/state.json* \
74
+ /data/workspace/subagent-window-states.json 2>/dev/null || true
75
+ if [ "$EKKO_DB_MIGRATED" = "1" ]; then
76
+ rm -rf /data/workspace/packages 2>/dev/null || true
77
+ fi
78
+
79
+ # Migrate legacy /data/config/* into the structured /data/apps/* layout (older revisions
80
+ # wrote app config here). Only drop the legacy copy once it is byte-identical to the
81
+ # migrated one, so a hand-edited legacy file is never silently discarded.
82
+ if [ -d /data/config ]; then
83
+ for legacy in /data/config/*/; do
84
+ [ -d "$legacy" ] || continue
85
+ name="$(basename "$legacy")"
86
+ mkdir -p "/data/apps/$name"
87
+ cp -rn "$legacy". "/data/apps/$name/" 2>/dev/null || true
88
+ stale=1
89
+ for f in "$legacy"*; do
90
+ [ -f "$f" ] || continue
91
+ cmp -s "$f" "/data/apps/$name/$(basename "$f")" || stale=0
92
+ done
93
+ if [ "$stale" = "1" ]; then
94
+ echo "🗑️ Removing legacy /data/config/$name (identical to /data/apps/$name)"
95
+ rm -rf "$legacy"
96
+ else
97
+ echo "⚠️ Keeping legacy /data/config/$name — differs from /data/apps/$name, review manually"
98
+ fi
99
+ done
100
+ rmdir /data/config 2>/dev/null || true
101
+ fi
102
+
103
+ # Legacy code-server user-data location; current user-data is /data/apps/vscode
104
+ rm -rf /data/code-server 2>/dev/null || true
105
 
106
  # Clean legacy logs/tmp and active SQLite DBs from FUSE bucket to prevent deadlocks
107
  rm -rf /data/logs /data/tmp /data/.cache /data/openclaw /data/script/codeman /data/.hermes /data/.hermes-web-ui /data/.ekko-studio /data/.ekko 2>/dev/null || true
 
118
  nohup python3 /app/services/apps_sync.py > /tmp/logs/apps-sync.log 2>&1 &
119
  fi
120
 
121
+ # code-server must always open BLANK: drop any restored "last opened folder" memory so
122
+ # /code/ never deep-links to ?folder=/data/workspace. Runs after apps_sync restore.
123
+ rm -rf /data/apps/vscode/User/workspaceStorage /data/apps/vscode/User/History /data/apps/vscode/Backups 2>/dev/null || true
124
+ mkdir -p /data/apps/vscode/User
125
+ cat > /data/apps/vscode/User/settings.json << 'SETEOF'
126
+ {
127
+ "workbench.startupEditor": "none",
128
+ "window.restoreWindows": "none"
129
+ }
130
+ SETEOF
131
+
132
  # Deploy clean opencode-router with assets and public UI into /data/script/opencode-router
133
  mkdir -p /data/script/opencode-router
134
  cp -rn /opt/opencode-router/* /data/script/opencode-router/ 2>/dev/null || true
135
  chmod +x /data/script/opencode-router/opencode-router 2>/dev/null || true
136
 
137
+ # Ship the already-fixed index.html (relative asset + API paths) instead of rewriting the
138
+ # HTML with sed at boot. See config/opencode-router/index.html — that file is the source
139
+ # of truth, so /opencode/ never hijacks the root /assets or /api namespaces.
140
+ mkdir -p /data/script/opencode-router/public
141
+ if [ -f /app/config/opencode-router/index.html ]; then
142
+ cp -f /app/config/opencode-router/index.html /data/script/opencode-router/public/index.html
143
+ else
144
+ echo "⚠️ /app/config/opencode-router/index.html missing; keeping router's bundled index.html"
 
145
  fi
146
 
147
+ # Redirect code-server caches & logs to /tmp so the S3 bucket never accumulates garbage
148
+ mkdir -p /data/apps/vscode
149
+ rm -rf /data/apps/vscode/CachedData /data/apps/vscode/CachedProfilesData /data/apps/vscode/CachedExtensionVSIXs /data/apps/vscode/logs 2>/dev/null || true
150
+ ln -sfn /tmp/logs /data/apps/vscode/logs 2>/dev/null || true
151
+ ln -sfn /tmp/code-server-cache /data/apps/vscode/CachedData 2>/dev/null || true
152
+ ln -sfn /tmp/code-server-cache/ProfilesData /data/apps/vscode/CachedProfilesData 2>/dev/null || true
 
 
153
 
154
  # 2. Persistent Caddyfile on /data (user-editable):
155
  # Always sync from template to apply latest routing rules and remove stale directives
services/02-setup-rea-agents.sh CHANGED
@@ -3,7 +3,7 @@
3
  # (Hermes, Claude Code, OpenCode, DeepSeek Harness, VS Code)
4
 
5
  LOG="/tmp/logs/setup-rea-agents.log"
6
- mkdir -p /tmp/logs /data/config/opencode /data/config/dsh /data/workspace/.vscode /root/.config
7
 
8
  echo "🔧 Configuring REA MCP across all coding agents..." > "$LOG"
9
 
 
3
  # (Hermes, Claude Code, OpenCode, DeepSeek Harness, VS Code)
4
 
5
  LOG="/tmp/logs/setup-rea-agents.log"
6
+ mkdir -p /tmp/logs /data/apps/{opencode,dsh,vscode/User,hermes} /root/.config
7
 
8
  echo "🔧 Configuring REA MCP across all coding agents..." > "$LOG"
9
 
services/05-code-server.sh CHANGED
@@ -13,7 +13,8 @@ if [ -f /data/.env ]; then
13
  fi
14
 
15
  export PASSWORD="${CODE_PASSWORD:-${AUTH_TOKEN:-}}"
16
- rm -f "$HOME/.config/code-server/config.yaml" "$USER_DATA/config.yaml" 2>/dev/null || true
 
17
 
18
  # Symlink heavy logs & CachedData to /tmp so S3 /data never fills
19
  ln -sfn /tmp/logs "$USER_DATA/logs" 2>/dev/null || true
 
13
  fi
14
 
15
  export PASSWORD="${CODE_PASSWORD:-${AUTH_TOKEN:-}}"
16
+ mkdir -p "$HOME/.config/code-server"
17
+ printf "bind-addr: 127.0.0.1:8443\nauth: password\npassword: %s\ncert: false\n" "$PASSWORD" > "$HOME/.config/code-server/config.yaml"
18
 
19
  # Symlink heavy logs & CachedData to /tmp so S3 /data never fills
20
  ln -sfn /tmp/logs "$USER_DATA/logs" 2>/dev/null || true
services/20-opencode-router.sh CHANGED
@@ -7,17 +7,6 @@ LOG="/tmp/logs/opencode-router.log"
7
 
8
  cp -rn /opt/opencode-router/* "$DIR/" 2>/dev/null || true
9
 
10
- # Ensure relative path resolution in public/index.html so /opencode doesn't hijack root /assets or /api
11
- INDEX_HTML="$DIR/public/index.html"
12
- if [ -f "$INDEX_HTML" ]; then
13
- sed -i 's|const basePath = window.location.pathname.replace(/\\/+$/, "");||g' "$INDEX_HTML" 2>/dev/null || true
14
- sed -i 's|<head><base href="/opencode/">|<head>|g' "$INDEX_HTML" 2>/dev/null || true
15
- sed -i 's|href="/assets/|href="assets/|g' "$INDEX_HTML" 2>/dev/null || true
16
- sed -i 's|src="/assets/|src="assets/|g' "$INDEX_HTML" 2>/dev/null || true
17
- sed -i 's|function api(path,|const basePath = window.location.pathname.replace(/\\/+$/, ""); function api(path,|g' "$INDEX_HTML" 2>/dev/null || true
18
- sed -i 's|return fetch(path,|const targetPath = basePath + (path.startsWith("/") ? path : "/" + path); return fetch(targetPath,|g' "$INDEX_HTML" 2>/dev/null || true
19
- fi
20
-
21
  # Do NOT overwrite existing config on /data; seed default only if missing
22
  if [ ! -f "$CONFIG" ]; then
23
  cat > "$CONFIG" << 'EOF'
@@ -69,6 +58,34 @@ if [ ! -f "$CONFIG" ]; then
69
  EOF
70
  fi
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  if pgrep -f "$DIR/opencode-router" >/dev/null 2>&1; then
73
  echo "opencode-router already running"
74
  exit 0
@@ -76,4 +93,4 @@ fi
76
 
77
  cd "$DIR" || exit 1
78
  chmod +x "$DIR/opencode-router" 2>/dev/null || true
79
- exec "$DIR/opencode-router" 8787 >> "$LOG" 2>&1
 
7
 
8
  cp -rn /opt/opencode-router/* "$DIR/" 2>/dev/null || true
9
 
 
 
 
 
 
 
 
 
 
 
 
10
  # Do NOT overwrite existing config on /data; seed default only if missing
11
  if [ ! -f "$CONFIG" ]; then
12
  cat > "$CONFIG" << 'EOF'
 
58
  EOF
59
  fi
60
 
61
+ # Ship the pre-fixed index.html (relative asset + API paths) from the repo instead of
62
+ # rewriting the HTML with sed on every start. Source of truth:
63
+ # config/opencode-router/index.html — keeps /opencode/ from hijacking root /assets or /api.
64
+ if [ -f /app/config/opencode-router/index.html ]; then
65
+ mkdir -p "$DIR/public"
66
+ cp -f /app/config/opencode-router/index.html "$DIR/public/index.html"
67
+ fi
68
+
69
+ # Prefill the UI's API key from the router config's proxyKey. The HTML committed to git
70
+ # carries no secret — the key is read back from the config that already holds it.
71
+ if [ -f "$DIR/public/index.html" ] && [ -f "$CONFIG" ]; then
72
+ python3 - "$DIR/public/index.html" "$CONFIG" <<'PREFILL_EOF' 2>/dev/null || true
73
+ import json, pathlib, sys
74
+ html_path, cfg_path = sys.argv[1], sys.argv[2]
75
+ try:
76
+ key = (json.load(open(cfg_path)) or {}).get("proxyKey") or ""
77
+ except Exception:
78
+ key = ""
79
+ if not key:
80
+ sys.exit(0)
81
+ needle = 'localStorage.getItem("opencodeKey") || ""'
82
+ p = pathlib.Path(html_path)
83
+ s = p.read_text(encoding="utf-8", errors="ignore")
84
+ if needle in s:
85
+ p.write_text(s.replace(needle, 'localStorage.getItem("opencodeKey") || ' + json.dumps(key), 1), encoding="utf-8")
86
+ PREFILL_EOF
87
+ fi
88
+
89
  if pgrep -f "$DIR/opencode-router" >/dev/null 2>&1; then
90
  echo "opencode-router already running"
91
  exit 0
 
93
 
94
  cd "$DIR" || exit 1
95
  chmod +x "$DIR/opencode-router" 2>/dev/null || true
96
+ exec "$DIR/opencode-router" 8787 >> "$LOG" 2>&1
services/25-ekko-studio.sh CHANGED
@@ -1,7 +1,7 @@
1
  #!/bin/bash
2
  # 25-ekko-studio.sh — Ekko Studio Web UI on internal port 7861
3
  DIR="/data/script/ekko-studio"
4
- mkdir -p "$DIR" /tmp/logs /tmp/.cache /data/.ekko-studio
5
  LOG="/tmp/logs/ekko-studio.log"
6
 
7
  if [ -f /tmp/.env ]; then
@@ -24,13 +24,18 @@ export HERMES_WEB_UI_HOME="/home/appuser/.hermes-web-ui"
24
  export AUTH_TOKEN="${AUTH_TOKEN:-${CODE_PASSWORD:-123456}}"
25
  export PASSWORD="$AUTH_TOKEN"
26
  export TMPDIR="/tmp"
 
 
 
 
 
27
 
28
  if pgrep -f "hermes-web-ui.*8648" >/dev/null 2>&1; then
29
  echo "ekko-studio already running"
30
  exit 0
31
  fi
32
 
33
- cd /data/workspace || exit 1
34
 
35
  # Launch Ekko Studio (packaged as hermes-web-ui)
36
  ENTRY="/opt/hermes-web-ui/dist/server/index.js"
 
1
  #!/bin/bash
2
  # 25-ekko-studio.sh — Ekko Studio Web UI on internal port 7861
3
  DIR="/data/script/ekko-studio"
4
+ mkdir -p "$DIR" /tmp/logs /tmp/.cache
5
  LOG="/tmp/logs/ekko-studio.log"
6
 
7
  if [ -f /tmp/.env ]; then
 
24
  export AUTH_TOKEN="${AUTH_TOKEN:-${CODE_PASSWORD:-123456}}"
25
  export PASSWORD="$AUTH_TOKEN"
26
  export TMPDIR="/tmp"
27
+ # Production mode: hermes-web-ui writes SQLite to HERMES_WEB_UI_HOME (fast local disk,
28
+ # backed up by apps_sync.py) instead of $CWD/packages/server/data (bucket /home path).
29
+ export NODE_ENV=production
30
+ export HERMES_WEB_UI_HOME="/home/appuser/.hermes-web-ui"
31
+ export HERMES_WEBUI_STATE_DIR="/home/appuser/.hermes-web-ui"
32
 
33
  if pgrep -f "hermes-web-ui.*8648" >/dev/null 2>&1; then
34
  echo "ekko-studio already running"
35
  exit 0
36
  fi
37
 
38
+ cd /home/appuser || exit 1
39
 
40
  # Launch Ekko Studio (packaged as hermes-web-ui)
41
  ENTRY="/opt/hermes-web-ui/dist/server/index.js"
services/28-hermes-agent.sh CHANGED
@@ -1,6 +1,6 @@
1
  #!/bin/bash
2
  # 28-hermes-agent.sh — Native Hermes Gateway with Telegram & REA MCP
3
- mkdir -p /data/.hermes /tmp/logs
4
  LOG="/tmp/logs/hermes-agent.log"
5
 
6
  if [ -f /tmp/.env ]; then
@@ -21,6 +21,10 @@ export API_SERVER_ENABLED=true
21
  export API_SERVER_PORT=8642
22
  export API_SERVER_HOST=127.0.0.1
23
  export GATEWAY_ALLOW_ALL_USERS=true
 
 
 
 
24
 
25
  # Seed hermes config if not present
26
  mkdir -p /home/appuser/.hermes
 
1
  #!/bin/bash
2
  # 28-hermes-agent.sh — Native Hermes Gateway with Telegram & REA MCP
3
+ mkdir -p /home/appuser/.hermes /tmp/logs
4
  LOG="/tmp/logs/hermes-agent.log"
5
 
6
  if [ -f /tmp/.env ]; then
 
21
  export API_SERVER_PORT=8642
22
  export API_SERVER_HOST=127.0.0.1
23
  export GATEWAY_ALLOW_ALL_USERS=true
24
+ # Production mode: hermes-web-ui writes its SQLite state to HERMES_WEB_UI_HOME instead of
25
+ # $CWD/packages/server/data (the gateway cwd is /data/workspace, i.e. the S3 bucket).
26
+ export NODE_ENV=production
27
+ export HERMES_WEB_UI_HOME="/home/appuser/.hermes-web-ui"
28
 
29
  # Seed hermes config if not present
30
  mkdir -p /home/appuser/.hermes