Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
309 lines (307 loc) · 59.6 KB
/
Copy pathindex.html
File metadata and controls
309 lines (307 loc) · 59.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#07090d">
<meta name="description" content="OCodeJS Server Control Center — dashboard staging cho services, AI agents, API, authentication, MCP, logs và tài liệu.">
<link rel="canonical" href="https://ocodejs.co/">
<title>OCodeJS Server — Control Center</title>
<style>
:root{color-scheme:dark;--bg:#07090d;--side:#090c12;--panel:#0d1119;--panel2:#111722;--line:#202938;--text:#eef2f8;--muted:#8390a3;--blue:#7194ff;--cyan:#6dd6dc;--green:#63d6a2;--amber:#f2bd68;--red:#f07f86;--mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace}
*{box-sizing:border-box}html,body{margin:0;min-height:100%;background:var(--bg);color:var(--text);font-family:var(--mono);font-size:13px}button,input,select,textarea{font:inherit}a{color:inherit;text-decoration:none}button{cursor:pointer;color:inherit}.app{min-height:100vh;display:grid;grid-template-columns:248px minmax(0,1fr)}.sidebar{background:var(--side);border-right:1px solid var(--line);padding:22px 14px;display:flex;flex-direction:column;min-height:100vh;position:sticky;top:0;height:100vh}.brand{display:flex;gap:11px;align-items:center;padding:0 10px 25px;border-bottom:1px solid var(--line)}.logo{width:34px;height:34px;border:1px solid #53617a;background:#111a2b;display:grid;place-items:center;color:#b9caff;font-weight:900}.brand strong{font-size:14px;letter-spacing:-.06em}.brand small{display:block;font-size:9px;color:var(--muted);letter-spacing:.14em;margin-top:4px}.nav-label{font-size:9px;color:#647187;letter-spacing:.16em;padding:22px 10px 8px}.nav{display:grid;gap:4px}.nav button{display:flex;align-items:center;gap:12px;text-align:left;border:1px solid transparent;background:transparent;color:#9ba7b9;padding:11px 10px;border-radius:5px;font-size:11px}.nav button:hover{background:#101722;color:#fff}.nav button.active{background:#142039;border-color:#253b65;color:#dce6ff}.ico{width:17px;text-align:center;color:#8ea9f5;font-size:14px}.side-bottom{margin-top:auto}.connection{border:1px solid var(--line);background:#0d131c;padding:12px;border-radius:5px}.connection small{color:var(--muted);font-size:9px;display:block}.connection strong{font-size:11px;display:block;margin:7px 0}.demo-pill{display:inline-flex;align-items:center;gap:6px;color:var(--amber);font-size:9px;border:1px solid #59482e;padding:4px 7px}.main{min-width:0}.topbar{height:68px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 30px;gap:18px;background:#080b10;position:sticky;top:0;z-index:10}.crumb{color:var(--muted);font-size:10px}.crumb b{color:#edf2fb;font-weight:600}.top-actions{display:flex;align-items:center;gap:10px}.search{background:#0d131c;border:1px solid var(--line);padding:9px 11px;color:#eaf0fb;width:min(250px,32vw);outline:none}.search:focus,input:focus,textarea:focus{border-color:#5577d2!important;outline:none}.avatar{width:30px;height:30px;border:1px solid #3a4b69;background:#15223a;color:#c9d8ff;display:grid;place-items:center;font-size:10px}.content{max-width:1440px;padding:30px;margin:auto}.page-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:24px}.eyebrow{font-size:9px;letter-spacing:.16em;color:var(--blue);text-transform:uppercase}.page-head h1{font-size:25px;letter-spacing:-.07em;margin:8px 0 6px}.page-head p{color:var(--muted);font-size:11px;margin:0;line-height:1.7}.btn{border:1px solid #3b4f75;background:#172642;color:#e5edff;padding:10px 13px;border-radius:4px;font-size:10px}.btn:hover{background:#20365e}.btn.ghost{background:transparent;border-color:var(--line);color:#aeb9ca}.btn.danger{border-color:#63363d;background:#271419;color:#ffb9bf}.grid{display:grid;gap:14px}.stats{grid-template-columns:repeat(4,minmax(0,1fr));margin-bottom:16px}.panel,.stat{background:var(--panel);border:1px solid var(--line);border-radius:5px;min-width:0}.stat{padding:17px}.stat-top{display:flex;justify-content:space-between;color:var(--muted);font-size:10px}.stat-value{font-size:25px;letter-spacing:-.07em;margin:14px 0 5px}.stat-foot{font-size:9px;color:var(--muted)}.stat-foot em{font-style:normal;color:var(--cyan)}.cols{grid-template-columns:minmax(0,1.5fr) minmax(260px,.9fr)}.panel-head{padding:16px 18px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:12px}.panel-head strong{font-size:11px}.panel-head small{font-size:9px;color:var(--muted)}.panel-body{padding:17px}.service-list{display:grid}.service{display:grid;grid-template-columns:1fr auto auto;gap:18px;align-items:center;padding:13px 0;border-bottom:1px solid #1b2431}.service:last-child{border:0}.service b{font-size:11px}.service small{display:block;color:var(--muted);font-size:9px;margin-top:5px}.state{font-size:9px;padding:4px 7px;border:1px solid #39465a;color:#b4c0d3;white-space:nowrap}.state.ok{color:var(--green);border-color:#275744}.state.warn{color:var(--amber);border-color:#604d2d}.state.off{color:#a1adbf;border-color:#39465a}.latency{font-size:10px;color:#aab6c8;white-space:nowrap}.chart{height:160px;display:flex;align-items:end;gap:8px;padding:15px 4px 22px;border-bottom:1px solid var(--line);background:repeating-linear-gradient(to bottom,transparent 0,transparent 38px,#1a2330 39px)}.bar{flex:1;min-width:4px;background:linear-gradient(180deg,#7798ff,#354d88);border-radius:2px 2px 0 0;position:relative}.bar:after{content:attr(data-label);position:absolute;bottom:-20px;left:50%;transform:translateX(-50%);font-size:8px;color:#738096}.feed{display:grid;gap:13px}.feed-item{display:flex;gap:10px;align-items:flex-start}.feed-dot{width:7px;height:7px;border-radius:50%;background:#667b9c;margin-top:4px;flex:none}.feed-item b{font-size:10px;font-weight:500}.feed-item small{display:block;color:var(--muted);font-size:9px;margin-top:4px}.notice{padding:11px 13px;border:1px solid #54452b;background:#17140e;color:#d7bd8b;font-size:10px;line-height:1.7;margin-bottom:16px}.cards{grid-template-columns:repeat(3,minmax(0,1fr))}.tile{padding:18px}.tile h3{font-size:12px;margin:0 0 7px}.tile p{font-size:10px;color:var(--muted);line-height:1.7;margin:0 0 14px}.tile-foot{display:flex;align-items:center;justify-content:space-between;gap:8px}.tag{font-size:8px;color:#a9b7ce;border:1px solid #303d52;padding:4px 6px}.table-wrap{overflow:auto}.table{width:100%;border-collapse:collapse;min-width:620px}.table th,.table td{text-align:left;padding:13px 15px;border-bottom:1px solid #1d2735;font-size:10px;white-space:nowrap}.table th{color:#718097;font-weight:500;font-size:9px;text-transform:uppercase;letter-spacing:.1em}.table td{color:#c4cede}.table code{color:#9db6ff;font-family:var(--mono)}.table tr:last-child td{border:0}.filters{display:flex;gap:8px;flex-wrap:wrap}.filters button{background:#0d131c;border:1px solid var(--line);padding:7px 10px;color:#8e9bb0;font-size:9px}.filters button.active{border-color:#536fae;color:#dce7ff;background:#14213a}.agent-icon{width:34px;height:34px;border:1px solid #344866;background:#121d30;display:grid;place-items:center;color:#a9c0ff}.agent-row{display:flex;gap:12px;align-items:center}.agent-row strong{font-size:11px}.agent-row small{display:block;color:var(--muted);font-size:9px;margin-top:4px}.api-path{color:#b8caff;font-size:10px}.method{font-size:8px;padding:4px 6px;border:1px solid #315b4a;color:#81dcb1}.method.post{border-color:#66512c;color:#e7c17e}.method.delete{border-color:#633b40;color:#f19ba2}.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.field{display:grid;gap:6px}.field.full{grid-column:1/-1}.field label{font-size:9px;color:#91a0b5}.field input,.field select,.field textarea{width:100%;background:#080d14;border:1px solid #293548;color:#e6edf8;padding:10px;border-radius:3px}.field textarea{min-height:90px;resize:vertical}.modal-backdrop{position:fixed;inset:0;background:#000b;display:none;align-items:center;justify-content:center;padding:18px;z-index:30}.modal-backdrop.show{display:flex}.modal{width:min(520px,100%);background:#0d131c;border:1px solid #33415a;border-radius:6px;box-shadow:0 25px 90px #000;padding:20px}.modal-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px}.modal-head strong{font-size:13px}.close{background:none;border:0;color:#93a0b4;font-size:20px}.modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:18px}.empty{padding:28px;text-align:center;color:var(--muted);font-size:10px}.doc-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.doc{border:1px solid var(--line);background:#0b1018;padding:17px;display:block}.doc:hover{border-color:#506a9d}.doc strong{font-size:11px}.doc p{font-size:9px;color:var(--muted);line-height:1.7}.doc span{font-size:9px;color:#9db6ff}.log{font-size:10px;color:#9cabc0;padding:9px 0;border-bottom:1px solid #1b2532;display:grid;grid-template-columns:75px 55px 1fr;gap:10px}.log code{color:#a9bfff}.mobile-menu{display:none}
@media(max-width:900px){.app{grid-template-columns:210px minmax(0,1fr)}.content{padding:22px}.stats{grid-template-columns:repeat(2,1fr)}.cards{grid-template-columns:repeat(2,1fr)}}
@media(max-width:650px){.app{display:block}.sidebar{position:fixed;z-index:25;left:-260px;top:0;width:248px;transition:left .2s;box-shadow:15px 0 50px #0008}.sidebar.open{left:0}.mobile-menu{display:inline-flex;background:transparent;border:1px solid var(--line);padding:8px 10px}.topbar{height:60px;padding:0 14px}.crumb{display:none}.search{width:42vw}.content{padding:20px 14px}.page-head{display:block}.page-head>.btn{margin-top:14px}.stats{gap:9px}.stat{padding:13px}.stat-value{font-size:21px}.cols,.cards,.doc-list{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr}.field.full{grid-column:auto}.service{gap:8px;grid-template-columns:1fr auto}.latency{display:none}.log{grid-template-columns:58px 45px 1fr;font-size:9px}.panel-body{padding:13px}}
</style>
<link rel="stylesheet" href="./ocodejs-design-system.css?v=1.0.0">
<link rel="stylesheet" href="./ocodejs-pages-theme.css?v=2.0.0">
<script>
window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };
</script>
<script defer src="/_vercel/insights/script.js"></script>
<!-- Vercel Web Analytics -->
<script defer src="https://cdn.vercel-insights.com/v1/script.js"></script>
</head>
<body>
<div class="app">
<aside class="sidebar" id="sidebar" aria-label="Điều hướng chính" aria-hidden="true" inert>
<div class="drawer-head"><div class="brand"><div class="logo">>_</div><div><strong>OCode.js</strong><small>SERVER CONTROL</small></div></div><button class="drawer-close" id="closeNav" type="button" aria-label="Đóng menu">×</button></div>
<div class="nav-label">WORKSPACE</div>
<nav class="nav" id="workspaceNavigation" aria-label="Dashboard navigation" data-navigation-registry></nav>
<div class="side-bottom"><div class="connection"><small>ENVIRONMENT</small><strong>Cloudflare · staging API</strong><span class="demo-pill">● STAGING</span></div></div>
</aside>
<main class="main">
<header class="topbar"><div class="top-actions"><button class="mobile-menu" id="mobileMenu" type="button" aria-label="Mở menu điều hướng" aria-controls="sidebar" aria-expanded="false"><span aria-hidden="true">☰</span></button><div class="crumb">OCodeJS / <b id="crumb">Server Dashboard</b></div></div><div class="top-actions"><input class="search" id="globalSearch" placeholder="Tìm trong trang hiện tại..." aria-label="Tìm kiếm"><div class="avatar" title="Preview">OC</div></div></header>
<div class="content" id="view"></div>
</main>
</div>
<button class="nav-scrim" id="navScrim" type="button" tabindex="-1" aria-label="Đóng menu"></button>
<div class="modal-backdrop" id="modal"><section class="modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle"><div class="modal-head"><strong id="modalTitle">Thêm kết nối</strong><button class="close" id="closeModal" aria-label="Đóng">×</button></div><form id="connectionForm"><div class="form-grid"><div class="field full"><label for="connName">Tên kết nối</label><input id="connName" required placeholder="Ví dụ: Local MCP"></div><div class="field"><label for="connType">Loại kết nối</label><select id="connType"><option>MCP Server</option><option>AI Provider</option><option>API Service</option></select></div><div class="field"><label for="connUrl">Endpoint URL</label><input id="connUrl" type="url" placeholder="https://..."></div><div class="field full"><label for="connNote">Ghi chú</label><textarea id="connNote" placeholder="Mô tả mục đích kết nối (không nhập token hoặc secret)"></textarea></div></div><p style="font-size:9px;color:#8c9ab0;line-height:1.7">Bản preview chỉ lưu trạng thái tạm trong trình duyệt hiện tại. Chưa gửi dữ liệu tới máy chủ.</p><div class="modal-actions"><button type="button" class="btn ghost" id="cancelModal">Hủy</button><button class="btn" type="submit">Thêm vào bản preview</button></div></form></section></div>
<script>
const viewRoot=document.getElementById('view');
const names={overview:'Server Dashboard',agents:'AI Agents',api:'API Gateway',auth:'Authentication',mcp:'MCP Server',console:'Developer Console',docs:'Documentation','service-registry':'Service Registry',providers:'Provider Registry',runtime:'AI Runtime'};
const navigationRegistry=[
{id:'overview',label:'Server Dashboard',icon:'▦',group:'WORKSPACE'},
{id:'agents',label:'AI Agents',icon:'✳',group:'WORKSPACE'},
{id:'api',label:'API Gateway',icon:'⌘',group:'WORKSPACE'},
{id:'auth',label:'Authentication',icon:'◈',group:'WORKSPACE'},
{id:'mcp',label:'MCP Server',icon:'⛓',group:'WORKSPACE'},
{id:'console',label:'Developer Console',icon:'▤',group:'WORKSPACE'},
{id:'docs',label:'Documentation',icon:'▧',group:'WORKSPACE'},
{id:'service-registry',label:'Service Registry',icon:'◉',group:'PLATFORM'},
{id:'providers',label:'Provider Registry',icon:'◈',group:'PLATFORM'},
{id:'runtime',label:'AI Runtime',icon:'✳',group:'PLATFORM'}
];
let current='overview',connections=[];
let dashboardRequestSequence=0;
let dashboardAbortController=null;
const CONTROL_API_BASE='https://ocodejs-server-api-staging.huynhthuongg2505-f9b.workers.dev/api/v1';
const MCP_ENDPOINT='https://ocodejs-mcp-staging.huynhthuongg2505-f9b.workers.dev/mcp';
const services=[['AI Agent Runtime','Điều phối tác vụ agent','Chưa kết nối','off','—'],['API Gateway','Định tuyến API & rate limits','Chưa kết nối','off','—'],['Identity / Auth','OAuth · session · account','Chưa kết nối','off','—'],['MCP Registry','Quản lý MCP endpoints','Chưa kết nối','off','—'],['Developer Telemetry','Logs · metrics · traces','Chưa kết nối','off','—']];
const endpoints=[['GET','/api/v1','API metadata và route index','STAGING LIVE'],['GET','/api/v1/health/live','Liveness probe','STAGING LIVE'],['GET','/api/v1/health/ready','Readiness probe','STAGING LIVE'],['GET','/api/v1/services','Service Registry','STAGING LIVE'],['GET','/api/v1/services/{serviceId}','Chi tiết một service','STAGING LIVE'],['GET','/api/v1/providers','Provider Registry (read-only)','STAGING LIVE'],['GET','/api/v1/providers/{providerId}','Provider adapter detail','STAGING LIVE'],['GET','/api/v1/agents','Agent Registry (read-only)','STAGING LIVE'],['GET','/api/v1/agents/{agentId}','Agent definition versioned','STAGING LIVE'],['GET','/api/v1/mcp/connections','MCP Connection Registry','STAGING LIVE'],['GET','/api/v1/mcp/connections/{connectionId}','MCP connection detail','STAGING LIVE']];
function header(kicker,title,desc,action=''){return '<div class="page-head"><div><div class="eyebrow">'+kicker+'</div><h1>'+title+'</h1><p>'+desc+'</p></div>'+action+'</div>'}
function panel(title,body,extra=''){return '<section class="panel"><div class="panel-head"><strong>'+title+'</strong>'+extra+'</div>'+body+'</section>'}
function overview(){return header('SYSTEM OVERVIEW / 00','Server Dashboard','Trạng thái dịch vụ được lấy trực tiếp từ OCodeJS Control API trên môi trường staging.')+
'<div class="notice" id="apiNotice" role="status" aria-live="polite">Đang kết nối Control API staging để tải trạng thái dịch vụ…</div>'+
'<div class="grid stats"><div class="stat"><div class="stat-top">Healthy services <span>◌</span></div><div class="stat-value" id="healthyCount">— / —</div><div class="stat-foot" id="serviceCountNote">Đang kiểm tra kết nối</div></div><div class="stat"><div class="stat-top">AI Agents <span>✳</span></div><div class="stat-value" id="agentCount">—</div><div class="stat-foot" id="agentCountNote">Chưa xác minh Agent Registry</div></div><div class="stat"><div class="stat-top">Control API <span>⌘</span></div><div class="stat-value" id="apiStateValue">CHECKING</div><div class="stat-foot">Cloudflare Workers · staging</div></div><div class="stat"><div class="stat-top">MCP Connections <span>⛓</span></div><div class="stat-value" id="mcpConnectionCount">—</div><div class="stat-foot" id="mcpConnectionCountNote">Chưa xác minh MCP Registry</div></div></div>'+
'<div class="grid cols">'+panel('SERVICE STATUS','<div class="panel-body service-list" id="serviceStatus" aria-live="polite"><div class="empty">Đang tải dữ liệu từ API…</div></div>','<div style="display:flex;align-items:center;gap:8px"><small id="apiHealthStatus">CHECKING</small><button class="btn ghost" id="refreshServices" type="button">↻ Refresh</button></div>')+
panel('CONTROL API HEALTH','<div class="panel-body feed"><div class="feed-item"><i class="feed-dot"></i><div><b id="apiHealthTitle">Đang kiểm tra API</b><small id="apiHealthDetail">GET /api/v1/health/live</small></div></div><div class="feed-item"><i class="feed-dot"></i><div><b>Readiness probe</b><small id="apiReadyDetail">GET /api/v1/health/ready · đang chờ</small></div></div><div class="feed-item"><i class="feed-dot"></i><div><b>Last checked</b><small id="apiCheckedAt">Chưa có dữ liệu</small></div></div></div>','<small>STAGING</small>')+
'</div><div style="height:14px"></div><div class="grid cols">'+panel('INTEGRATION STATUS','<div class="panel-body feed"><div class="feed-item"><i class="feed-dot"></i><div><b>Control API</b><small>Đã triển khai trên Cloudflare Workers staging</small></div></div><div class="feed-item"><i class="feed-dot"></i><div><b>Identity · AI Runtime · MCP · Telemetry</b><small>Chưa tích hợp health adapter; không được tính là healthy</small></div></div></div>')+panel('QUICK ACCESS','<div class="panel-body feed"><button class="btn ghost" data-go="agents">Mở AI Agents →</button><button class="btn ghost" data-go="api">Xem API Catalog →</button><button class="btn ghost" data-go="mcp">Quản lý MCP →</button><button class="btn ghost" data-go="docs">Đọc tài liệu →</button></div>')+'</div>'}
async function refreshDashboard(){
const requestId=++dashboardRequestSequence;
if(dashboardAbortController)dashboardAbortController.abort();
dashboardAbortController=new AbortController();
const button=document.getElementById('refreshServices');
const notice=document.getElementById('apiNotice');
if(!notice)return;
if(button){button.disabled=true;button.textContent='… Checking';}
const setText=(id,value)=>{const el=document.getElementById(id);if(el)el.textContent=value;};
const target=document.getElementById('serviceStatus');
if(target)target.innerHTML='<div class="empty">Đang xác minh dữ liệu mới từ Control API staging…</div>';
setText('healthyCount','— / —');
setText('serviceCountNote','Đang chờ dữ liệu mới · không dùng cache');
setText('apiStateValue','CHECKING');setText('apiHealthStatus','CHECKING');
setText('apiHealthTitle','Đang kiểm tra Control API');
setText('apiHealthDetail','GET '+CONTROL_API_BASE+'/health/live');
setText('apiReadyDetail','Readiness chưa xác minh');setText('apiCheckedAt','Chưa có snapshot mới');
notice.textContent='Đang kiểm tra kết nối. Dashboard chỉ hiển thị dữ liệu của lần xác minh hiện tại.';
notice.style.borderColor='#54452b';notice.style.background='#17140e';notice.style.color='#d7bd8b';
try{
const options={method:'GET',cache:'no-store',headers:{'Accept':'application/json'},signal:dashboardAbortController.signal};
const responses=await Promise.all([fetch(CONTROL_API_BASE+'/health/live',options),fetch(CONTROL_API_BASE+'/health/ready',options),fetch(CONTROL_API_BASE+'/services',options)]);
if(requestId!==dashboardRequestSequence)return;
if(responses.some(response=>!response.ok))throw new Error('HTTP '+responses.map(response=>response.status).join('/'));
const bodies=await Promise.all(responses.map(response=>response.json()));
const live=bodies[0],ready=bodies[1],registry=bodies[2];
if(live.live!==true||live.service!=='control-api'||ready.ready!==true||!Array.isArray(registry.services))throw new Error('API response schema or health contract is invalid');
const checkedAt=Date.parse(registry.checkedAt||''),ageMs=Date.now()-checkedAt;
if(!Number.isFinite(checkedAt)||ageMs < -15000||ageMs > 60000)throw new Error('API snapshot is missing, future-dated, or older than 60 seconds');
const allowedStates=new Set(['healthy','degraded','unavailable','not_configured','unknown']);
if(registry.services.some(item=>!item||typeof item.id!=='string'||typeof item.name!=='string'||!allowedStates.has(item.state)))throw new Error('Service Registry contains an invalid or unverified service state');
const labels={healthy:'HEALTHY',degraded:'DEGRADED',unavailable:'UNAVAILABLE',not_configured:'NOT CONFIGURED',unknown:'UNKNOWN'};
const classes={healthy:'ok',degraded:'warn',unavailable:'off',not_configured:'off',unknown:'off'};
const healthy=registry.services.filter(item=>item.state==='healthy').length;
if(target)target.innerHTML=registry.services.map(item=>'<div class="service"><div><b>'+escapeHtml(item.name)+'</b><small>'+escapeHtml(item.description||'')+'</small></div><span class="state '+(classes[item.state]||'off')+'">'+(labels[item.state]||'UNKNOWN')+'</span><span class="latency">'+(Number.isFinite(item.latencyMs)?item.latencyMs+' ms':'—')+'</span></div>').join('')||'<div class="empty">API chưa đăng ký dịch vụ nào.</div>';
setText('healthyCount',healthy+' / '+registry.services.length);
setText('serviceCountNote','Healthy theo snapshot mới · '+Math.round(ageMs/1000)+' giây');
const [agentResult,mcpResult]=await Promise.allSettled([
fetch(CONTROL_API_BASE+'/agents',options).then(response=>{if(!response.ok)throw new Error('HTTP '+response.status);return response.json();}),
fetch(CONTROL_API_BASE+'/mcp/connections',options).then(response=>{if(!response.ok)throw new Error('HTTP '+response.status);return response.json();})
]);
if(requestId!==dashboardRequestSequence)return;
if(agentResult.status==='fulfilled'&&Array.isArray(agentResult.value.agents)){
setText('agentCount',String(agentResult.value.agents.length));
setText('agentCountNote','Agent Registry · dữ liệu vừa tải');
}else{
setText('agentCount','—');setText('agentCountNote','Agent Registry chưa xác minh');
}
if(mcpResult.status==='fulfilled'&&Array.isArray(mcpResult.value.connections)){
setText('mcpConnectionCount',String(mcpResult.value.connections.length));
setText('mcpConnectionCountNote','MCP Registry · dữ liệu vừa tải');
}else{
setText('mcpConnectionCount','—');setText('mcpConnectionCountNote','MCP Registry chưa xác minh');
}
setText('apiStateValue','ONLINE');setText('apiHealthStatus','API ONLINE');
setText('apiHealthTitle','Control API đang phản hồi');
setText('apiHealthDetail','HTTP '+responses[0].status+' · '+live.service+' · v'+String(live.version||'unknown'));
setText('apiReadyDetail','READY · stateless API');setText('apiCheckedAt',new Date(checkedAt).toLocaleString('vi-VN'));
notice.textContent='Đã xác minh snapshot mới từ Control API staging. '+healthy+'/'+registry.services.length+' dịch vụ được API đánh dấu healthy; trạng thái không xác minh không được nâng lên healthy.';
notice.style.borderColor='#275744';notice.style.background='#0d1915';notice.style.color='#9be2bf';
}catch(error){
if(error&&error.name==='AbortError')return;
if(requestId!==dashboardRequestSequence)return;
if(target)target.innerHTML='<div class="empty">Không có dữ liệu Service Registry đã xác minh. Kiểm tra mạng, DNS, CORS hoặc API staging rồi nhấn Refresh.</div>';
setText('healthyCount','— / —');setText('serviceCountNote','Không có snapshot hợp lệ');
setText('agentCount','—');setText('agentCountNote','Agent Registry chưa xác minh');
setText('mcpConnectionCount','—');setText('mcpConnectionCountNote','MCP Registry chưa xác minh');
setText('apiStateValue','UNVERIFIED');setText('apiHealthStatus','API UNVERIFIED');
setText('apiHealthTitle','Không xác minh được Control API');
setText('apiHealthDetail','GET '+CONTROL_API_BASE+'/health/live');
setText('apiReadyDetail','Readiness chưa xác minh');
setText('apiCheckedAt','Lỗi: '+(error&&error.message?error.message:'network error'));
notice.textContent='Không kết nối hoặc không xác minh được Control API staging. Dashboard đã xóa dữ liệu cũ và không tự gán trạng thái healthy.';
notice.style.borderColor='#633b40';notice.style.background='#1b1013';notice.style.color='#f3a5ad';
}finally{if(requestId===dashboardRequestSequence&&button){button.disabled=false;button.textContent='↻ Refresh';}}
}
function agentView(){return header('AI PLATFORM / 01','AI Agents','Agent Registry và Provider Registry từ Control API; runtime chỉ được bật sau cấu hình và phê duyệt rõ ràng.','<button class="btn ghost" id="refreshAgents" type="button">↻ Refresh</button>')+'<div class="notice">Các agent đang ở trạng thái DRAFT. Provider Registry chỉ hiển thị adapter khả dụng; chưa có AI binding, chưa có lượt inference và chưa phát sinh chi phí model.</div><div id="agentRuntimeStatus" class="notice" style="margin-top:12px">Đang kiểm tra AI Runtime…</div><h3 class="section-title">PROVIDER REGISTRY</h3><div id="providerRegistry" class="grid cards"><div class="empty">Đang tải Provider Registry…</div></div><h3 class="section-title" style="margin-top:22px">AGENT DEFINITIONS</h3><div id="agentRegistry" class="grid cards"><div class="empty">Đang tải Agent Registry từ staging Control API…</div></div>'}
async function refreshAgentRegistry(){
const target=document.getElementById('agentRegistry');
const providerTarget=document.getElementById('providerRegistry');
const button=document.getElementById('refreshAgents');
if(!target)return;
if(button){button.disabled=true;button.textContent='… Loading';}
try{
const options={method:'GET',cache:'no-store',headers:{'Accept':'application/json'}};
const [agentResponse,providerResponse,runtimeResponse]=await Promise.all([
fetch(CONTROL_API_BASE+'/agents',options),
fetch(CONTROL_API_BASE+'/providers',options),
fetch(CONTROL_API_BASE+'/runtime/status',options)
]);
if(!agentResponse.ok||!providerResponse.ok||!runtimeResponse.ok)throw new Error('HTTP '+agentResponse.status+'/'+providerResponse.status+'/'+runtimeResponse.status);
const [body,providerBody,runtimeBody]=await Promise.all([agentResponse.json(),providerResponse.json(),runtimeResponse.json()]);
const runtimeTarget=document.getElementById('agentRuntimeStatus');
if(runtimeTarget){const runtime=runtimeBody.runtime;runtimeTarget.textContent='AI RUNTIME: '+String(runtime.state).toUpperCase()+' · PROVIDER: '+runtime.provider.state+' · RUN STORE: '+runtime.runStore.state+' · INFERENCE: DISABLED · AGENT EXECUTION: DISABLED';}
if(!Array.isArray(body.agents)||!Array.isArray(providerBody.providers))throw new Error('Registry schema không hợp lệ');
if(providerTarget)providerTarget.innerHTML=providerBody.providers.map(provider=>'<article class="panel tile"><div class="agent-row"><div class="agent-icon">◈</div><div><strong>'+escapeHtml(provider.name)+'</strong><small>'+escapeHtml(provider.id)+' · '+escapeHtml(provider.kind)+'</small></div></div><p style="margin-top:16px">'+escapeHtml(provider.description)+'</p><div class="tile-foot"><span class="state off">'+escapeHtml(provider.state.toUpperCase().replace('_',' '))+'</span><span class="tag">INFERENCE DISABLED</span></div><p style="font-size:10px;color:var(--muted);margin-top:12px">Capabilities: '+provider.capabilities.map(escapeHtml).join(' · ')+'</p><p style="font-size:10px;color:var(--muted)">Explicit enablement required: '+(provider.requiresExplicitEnablement?'YES':'NO')+'</p></article>').join('')||'<div class="empty">Chưa có provider adapter nào được catalog.</div>';
target.innerHTML=body.agents.map((agent,i)=>'<article class="panel tile"><div class="agent-row"><div class="agent-icon">'+['✳','⌘','◇'][i%3]+'</div><div><strong>'+escapeHtml(agent.name)+'</strong><small>'+escapeHtml(agent.id)+' · v'+escapeHtml(agent.version)+'</small></div></div><p style="margin-top:16px">'+escapeHtml(agent.description)+'</p><div class="tile-foot"><span class="state warn">'+escapeHtml(agent.status.toUpperCase())+'</span><span class="tag">RUNTIME DISABLED</span></div><p style="font-size:10px;color:var(--muted);margin-top:12px">Capabilities: '+agent.capabilities.map(escapeHtml).join(' · ')+'</p><p style="font-size:10px;color:var(--muted)">Provider: '+escapeHtml(agent.provider.state)+' · Tools: '+agent.tools.length+' · Approval required: '+(agent.approvalRequired?'YES':'NO')+'</p></article>').join('')||'<div class="empty">Agent Registry chưa có định nghĩa nào.</div>';
}catch(error){
target.innerHTML='<div class="empty">Không tải được Agent Registry từ staging API. Không hiển thị agent mẫu hoặc trạng thái giả. Lỗi: '+escapeHtml(error.message)+'</div>';
if(providerTarget)providerTarget.innerHTML='<div class="empty">Không tải được Provider Registry: '+escapeHtml(error.message)+'</div>';
}finally{if(button){button.disabled=false;button.textContent='↻ Refresh';}}
}
function serviceRegistryView(){return header('PLATFORM / 07','Service Registry','Danh mục dịch vụ và trạng thái health lấy trực tiếp từ Control API staging.','<button class="btn ghost" id="refreshServiceRegistry" type="button">↻ Refresh</button>')+'<div class="notice">Trạng thái được lấy theo từng lần kiểm tra. NOT CONFIGURED và UNKNOWN không được xem là healthy.</div><div class="grid stats"><div class="stat"><div class="stat-top">Registered services</div><div class="stat-value" id="registryTotal">—</div><div class="stat-foot">Control API registry</div></div><div class="stat"><div class="stat-top">Healthy</div><div class="stat-value" id="registryHealthy">—</div><div class="stat-foot">Đã xác minh healthy</div></div><div class="stat"><div class="stat-top">Degraded</div><div class="stat-value" id="registryDegraded">—</div><div class="stat-foot">Cần theo dõi</div></div><div class="stat"><div class="stat-top">Not ready</div><div class="stat-value" id="registryNotReady">—</div><div class="stat-foot">Unavailable / unknown / not configured</div></div></div>'+panel('REGISTERED SERVICES','<div id="serviceRegistryRows" class="panel-body service-list"><div class="empty">Đang tải registry…</div></div>','<small id="serviceRegistryChecked">STAGING</small>')+'<p id="serviceRegistryError" class="stat-foot" role="status" aria-live="polite"></p>'}
async function refreshServiceRegistry(){const target=document.getElementById('serviceRegistryRows');const button=document.getElementById('refreshServiceRegistry');if(!target)return;if(button){button.disabled=true;button.textContent='… Loading';}try{const response=await fetch(CONTROL_API_BASE+'/services',{method:'GET',cache:'no-store',headers:{Accept:'application/json'}});if(!response.ok)throw new Error('HTTP '+response.status);const body=await response.json();if(!Array.isArray(body.services))throw new Error('Service Registry schema không hợp lệ');const count=state=>body.services.filter(item=>item.state===state).length;const set=(id,value)=>{const el=document.getElementById(id);if(el)el.textContent=String(value)};set('registryTotal',body.count??body.services.length);set('registryHealthy',count('healthy'));set('registryDegraded',count('degraded'));set('registryNotReady',body.services.length-count('healthy')-count('degraded'));set('serviceRegistryChecked','CHECKED '+new Date(body.checkedAt||Date.now()).toLocaleString('vi-VN'));const labels={healthy:'HEALTHY',degraded:'DEGRADED',unavailable:'UNAVAILABLE',not_configured:'NOT CONFIGURED',unknown:'UNKNOWN'};const classes={healthy:'ok',degraded:'warn',unavailable:'off',not_configured:'off',unknown:'off'};target.innerHTML=body.services.map(item=>'<div class="service"><div><b>'+escapeHtml(item.name)+'</b><small>'+escapeHtml(item.id)+' · '+escapeHtml(item.description)+'</small><small>Source: '+escapeHtml(item.source||'unknown')+(item.latencyMs!=null?' · '+Number(item.latencyMs)+' ms':'')+'</small></div><span class="state '+(classes[item.state]||'off')+'">'+escapeHtml(labels[item.state]||String(item.state).toUpperCase())+'</span></div>').join('')||'<div class="empty">Registry chưa có service.</div>';const err=document.getElementById('serviceRegistryError');if(err)err.textContent='Request ID: '+String(body.requestId||'not supplied');}catch(error){target.innerHTML='<div class="empty">Không thể tải Service Registry. '+escapeHtml(error.message)+'</div>';const err=document.getElementById('serviceRegistryError');if(err)err.textContent='Không có dữ liệu cache hoặc mẫu thay thế.';}finally{if(button){button.disabled=false;button.textContent='↻ Refresh';}}}
function providersView(){return header('AI PLATFORM / 08','Provider Registry','Các provider đã được catalog. Trang này chỉ đọc metadata, không bật inference.','<button class="btn ghost" id="refreshProviders" type="button">↻ Refresh</button>')+'<div class="notice">Provider chỉ được xem là sẵn sàng sau khi có binding server-side, kiểm soát quota và phê duyệt bật runtime. Không có secret nào được hiển thị ở đây.</div><div id="providerRegistryPage" class="grid cards"><div class="empty">Đang tải Provider Registry…</div></div>'}
async function refreshProviders(){
const target=document.getElementById('providerRegistryPage');
const button=document.getElementById('refreshProviders');
if(!target)return;
if(button){button.disabled=true;button.textContent='… Loading';}
try{
const response=await fetch(CONTROL_API_BASE+'/providers',{method:'GET',cache:'no-store',headers:{Accept:'application/json'}});
if(!response.ok)throw new Error('HTTP '+response.status);
const body=await response.json();
if(!Array.isArray(body.providers))throw new Error('Provider Registry schema không hợp lệ');
const cards=body.providers.map(provider=>{
const state=String(provider.state||'unknown').toUpperCase().replace(/_/g,' ');
const capabilities=Array.isArray(provider.capabilities)?provider.capabilities.map(escapeHtml).join(' · '):'—';
const enabled=provider.executionEnabled===true;
const explicit=provider.requiresExplicitEnablement===true;
return '<article class="panel tile"><div class="agent-row"><div class="agent-icon">◈</div><div><strong>'+escapeHtml(provider.name)+'</strong><small>'+escapeHtml(provider.id)+' · '+escapeHtml(provider.kind)+'</small></div></div>'+
'<p style="margin-top:16px">'+escapeHtml(provider.description)+'</p>'+
'<div class="tile-foot"><span class="state '+(provider.state==='healthy'?'ok':'off')+'">'+escapeHtml(state)+'</span><span class="tag">'+(enabled?'EXECUTION ENABLED':'INFERENCE DISABLED')+'</span></div>'+
'<p style="font-size:10px;color:var(--muted);margin-top:12px">Capabilities: '+capabilities+'</p>'+
'<p style="font-size:10px;color:var(--muted)">Explicit enablement required: '+(explicit?'YES':'NO')+'</p></article>';
});
target.innerHTML=cards.join('')||'<div class="empty">Chưa có provider nào được catalog.</div>';
}catch(error){
target.innerHTML='<div class="empty">Không thể tải Provider Registry: '+escapeHtml(error.message)+'</div>';
}finally{
if(button){button.disabled=false;button.textContent='↻ Refresh';}
}
}
function runtimeView(){return header('AI PLATFORM / 09','AI Runtime','Theo dõi readiness của inference, provider và run store. Không thực thi agent từ màn hình này.','<button class="btn ghost" id="refreshRuntime" type="button">↻ Refresh</button>')+'<div class="notice">Safety gate: inference và agent execution tiếp tục bị khóa cho đến khi provider, run store, quota, authentication và approval controls được cấu hình.</div>'+panel('RUNTIME READINESS','<div id="runtimeReadiness" class="panel-body service-list"><div class="empty">Đang kiểm tra runtime…</div></div>')+'<div style="height:14px"></div>'+panel('EXECUTION POLICY','<div class="panel-body service-list"><div class="service"><div><b>Model inference</b><small>Không có yêu cầu inference được thực thi</small></div><span class="state off">DISABLED</span></div><div class="service"><div><b>Agent execution</b><small>Agent definitions ở trạng thái draft</small></div><span class="state off">DISABLED</span></div><div class="service"><div><b>Human approval</b><small>Yêu cầu phê duyệt rõ ràng trước khi bật</small></div><span class="state warn">REQUIRED</span></div></div>')+'<p id="runtimeCheckedAt" class="stat-foot" role="status" aria-live="polite"></p>'}
async function refreshRuntime(){const target=document.getElementById('runtimeReadiness'),button=document.getElementById('refreshRuntime');if(!target)return;if(button){button.disabled=true;button.textContent='… Checking';}try{const response=await fetch(CONTROL_API_BASE+'/runtime/status',{method:'GET',cache:'no-store',headers:{Accept:'application/json'}});if(!response.ok)throw new Error('HTTP '+response.status);const body=await response.json();const runtime=body.runtime;if(!runtime)throw new Error('Runtime status schema không hợp lệ');const rows=[['Runtime state',String(runtime.state).toUpperCase().replaceAll('_',' '),runtime.state==='healthy'?'ok':'off'],['Selected provider',String(runtime.provider?.id||'None'),runtime.provider?.state==='healthy'?'ok':'off'],['Catalogued providers',(runtime.cataloguedProviders||[]).join(', ')||'None','off'],['Configured providers',(runtime.configuredProviders||[]).join(', ')||'None','off'],['Run store',String(runtime.runStore?.state||'unknown').toUpperCase().replaceAll('_',' '),'off'],['Run lifecycle',String(runtime.runLifecycle||'unknown').toUpperCase(),'off'],['Inference',runtime.inferenceEnabled?'ENABLED':'DISABLED',runtime.inferenceEnabled?'warn':'off'],['Agent execution',runtime.executionEnabled?'ENABLED':'DISABLED',runtime.executionEnabled?'warn':'off'],['Approval required',runtime.approvalRequired?'YES':'NO',runtime.approvalRequired?'warn':'off']];target.innerHTML=rows.map(row=>'<div class="service"><div><b>'+escapeHtml(row[0])+'</b></div><span class="state '+row[2]+'">'+escapeHtml(row[1])+'</span></div>').join('')+'<p style="font-size:10px;color:var(--muted);line-height:1.7;margin-top:12px">'+escapeHtml(runtime.reason||'No additional runtime note.')+'</p>';const checked=document.getElementById('runtimeCheckedAt');if(checked)checked.textContent='Checked: '+new Date(body.checkedAt||Date.now()).toLocaleString('vi-VN')+' · Request ID: '+String(body.requestId||'not supplied');}catch(error){target.innerHTML='<div class="empty">Không thể tải runtime readiness: '+escapeHtml(error.message)+'</div>';}finally{if(button){button.disabled=false;button.textContent='↻ Refresh';}}}
function apiView(){return header('NETWORK / 02','API Gateway','Các route Control API hiện đã triển khai trên Cloudflare Workers staging.')+'<div class="notice">Các route bên dưới là API đọc dữ liệu đã có trên staging. Agent và Provider Registry đã có GET-only; Auth, MCP mutation và Agent Run APIs vẫn chưa được triển khai.</div>'+panel('ENDPOINT CATALOG','<div class="table-wrap"><table class="table"><thead><tr><th>Method</th><th>Endpoint</th><th>Mô tả</th><th>Availability</th></tr></thead><tbody>'+endpoints.map(e=>'<tr><td><span class="method '+(e[0]==='POST'?'post':e[0]==='DELETE'?'delete':'')+'">'+e[0]+'</span></td><td class="api-path">'+e[1]+'</td><td>'+e[2]+'</td><td><span class="state off">'+e[3]+'</span></td></tr>').join('')+'</tbody></table></div>','<small>11 ROUTES</small>')+'<div style="height:14px"></div><div class="grid cards"><article class="panel tile"><h3>Authentication</h3><p>Bearer token hoặc session cookie; cần triển khai middleware và policy.</p><span class="tag">DESIGN REQUIRED</span></article><article class="panel tile"><h3>Rate limiting</h3><p>Giới hạn theo API key, user hoặc client ID; cấu hình Redis/edge storage.</p><span class="tag">DESIGN REQUIRED</span></article><article class="panel tile"><h3>Observability</h3><p>Request ID, structured logs, latency và error metrics.</p><span class="tag">DESIGN REQUIRED</span></article></div>'}
function authView(){return header('IDENTITY / 03','Authentication','Theo dõi riêng Account Portal và dịch vụ GitHub OAuth dành cho OCodeJS CLI.')+
'<div class="notice">ĐĂNG NHẬP TẠM KHÓA — Cloudflare Preview build đã thành công, nhưng chưa có PostgreSQL riêng và OAuth secrets; health endpoint chưa được xác minh. Không gửi mật khẩu, token hoặc OAuth secret tại trang này.</div>'+
'<div class="grid cols"><section class="panel"><div class="panel-head"><strong>ACCOUNT SIGN IN</strong><span class="state off">NOT READY</span></div><div class="panel-body"><div class="field"><label>Email address</label><input disabled placeholder="you@example.com"></div><div class="field" style="margin-top:12px"><label>Password</label><input disabled type="password" placeholder="••••••••••"></div><button class="btn" disabled style="width:100%;margin-top:16px;opacity:.45">Đăng nhập · chờ Auth.js Preview</button><div style="display:flex;gap:8px;margin-top:12px"><button class="btn ghost" disabled style="flex:1;opacity:.45">Continue with GitHub</button><button class="btn ghost" disabled style="flex:1;opacity:.45">Continue with Google</button></div><p style="font-size:9px;color:var(--muted);line-height:1.7;margin-top:14px">Không kết nối form này với CLI PAT/OAuth. Hai hệ thống có mục đích và session riêng.</p></div></section>'+
'<section class="panel"><div class="panel-head"><strong>AUTH SERVICE HEALTH</strong><button class="btn ghost" id="refreshAuth" type="button">↻ Refresh</button></div><div class="panel-body service-list"><div class="service"><div><b>Account Portal · Auth.js</b><small id="accountAuthDetail">Backend chưa được triển khai</small></div><span class="state off" id="accountAuthStatus">NOT CONFIGURED</span></div><div class="service"><div><b>OCodeJS CLI · GitHub OAuth/PAT</b><small id="cliAuthDetail">Đang kiểm tra health endpoint…</small></div><span class="state off" id="cliAuthStatus">CHECKING</span></div><p id="authCheckedAt" style="font-size:9px;color:var(--muted);line-height:1.7">Health status được lấy từ Control API staging.</p></div></section></div>'}
async function refreshAuthReadiness(){
const button=document.getElementById('refreshAuth');
if(button)button.onclick=refreshAuthReadiness;
const setText=(id,value)=>{const el=document.getElementById(id);if(el)el.textContent=value;};
const setState=(id,state)=>{const el=document.getElementById(id);if(!el)return;el.textContent=state.toUpperCase().replace('_',' ');el.className='state '+(state==='healthy'?'ok':state==='degraded'?'warn':'off');};
if(button){button.disabled=true;button.textContent='… Checking';}
try{
const options={method:'GET',cache:'no-store',headers:{'Accept':'application/json'}};
const [identityResponse,cliResponse]=await Promise.all([
fetch(CONTROL_API_BASE+'/services/identity',options),
fetch(CONTROL_API_BASE+'/services/cli-auth',options)
]);
if(!identityResponse.ok||!cliResponse.ok)throw new Error('HTTP '+identityResponse.status+'/'+cliResponse.status);
const [identity,cli]=await Promise.all([identityResponse.json(),cliResponse.json()]);
setState('accountAuthStatus',identity.service.state);
setText('accountAuthDetail',identity.service.description);
setState('cliAuthStatus',cli.service.state);
setText('cliAuthDetail',cli.service.description);
setText('authCheckedAt','Last checked: '+new Date(cli.service.checkedAt||Date.now()).toLocaleString('vi-VN'));
}catch(error){
setState('accountAuthStatus','not_configured');
setText('accountAuthDetail','Auth.js Preview chưa được xác minh.');
setState('cliAuthStatus','unknown');
setText('cliAuthDetail','Không lấy được trạng thái từ Control API.');
setText('authCheckedAt','Lỗi kiểm tra: '+(error&&error.message?error.message:'network error'));
}finally{if(button){button.disabled=false;button.textContent='↻ Refresh';}}
}
function mcpView(){return header('CONNECTIVITY / 04','MCP Server','MCP staging endpoint đã được triển khai riêng; kiểm tra handshake và danh sách connection qua Control API.', '<button class="btn ghost" id="refreshMcpConnections" type="button">↻ Refresh registry</button>')+
panel('STAGING MCP ENDPOINT','<div class="panel-body"><div class="service"><div><b>OCode.js Control Center MCP</b><small><code>https://ocodejs-mcp-staging.huynhthuongg2505-f9b.workers.dev/mcp</code></small></div><span class="state warn" id="mcpStatus">HANDSHAKE PENDING</span></div><div class="filters" style="margin-top:15px"><button class="active" id="mcpInitialize">▶ Initialize</button><button id="mcpTools">Tools / List</button></div><pre id="mcpResult" style="white-space:pre-wrap;overflow-wrap:anywhere;background:#080d14;border:1px solid #293548;padding:12px;color:#aebbd0;font-size:10px;line-height:1.7;margin:14px 0 0">Chưa chạy handshake trực tiếp từ trình duyệt.</pre></div>','<small>ISOLATED STAGING</small>')+
'<div style="height:14px"></div>'+panel('MCP CONNECTIONS','<div id="mcpConnections" class="empty">Đang tải MCP Connection Registry…</div>','<small>READ-ONLY REGISTRY</small>')+
'<div style="height:14px"></div><div class="grid cards"><article class="panel tile"><h3>Transport</h3><p>Streamable HTTP, JSON-RPC 2.0; endpoint chỉ nhận POST.</p><span class="tag">MCP TRANSPORT</span></article><article class="panel tile"><h3>Read-only tools</h3><p>Đọc health, services, agent definitions và provider catalog. Không chạy model, không thực thi agent hoặc ghi dữ liệu.</p><span class="tag">6 TOOLS</span></article><article class="panel tile"><h3>Security boundary</h3><p>Đích backend cố định; không nhận URL tùy ý, không truy cập secrets hoặc DNS.</p><span class="tag">ALLOWLIST</span></article></div>'}
async function refreshMcpConnections(){
const target=document.getElementById('mcpConnections');
const button=document.getElementById('refreshMcpConnections');
if(!target)return;
if(button){button.disabled=true;button.textContent='… Loading';}
try{
const response=await fetch(CONTROL_API_BASE+'/mcp/connections',{method:'GET',cache:'no-store',headers:{'Accept':'application/json'}});
if(!response.ok)throw new Error('HTTP '+response.status);
const body=await response.json();
if(!Array.isArray(body.connections))throw new Error('MCP Registry schema không hợp lệ');
target.innerHTML='<div class="table-wrap"><table class="table"><thead><tr><th>Name</th><th>Transport</th><th>Endpoint</th><th>Status</th><th>Tools</th></tr></thead><tbody>'+body.connections.map(c=>'<tr><td>'+escapeHtml(c.name)+'<small style="display:block;color:var(--muted)">'+escapeHtml(c.id)+' · '+escapeHtml(c.environment)+'</small></td><td>'+escapeHtml(c.transport)+'</td><td><code>'+escapeHtml(c.endpoint)+'</code></td><td><span class="state '+(c.state==='healthy'?'on':'warn')+'">'+escapeHtml(c.state.toUpperCase())+'</span></td><td>'+Number(c.toolCount||0)+'</td></tr>').join('')+'</tbody></table></div>';
}catch(error){
target.innerHTML='<div class="empty">Không tải được MCP Connection Registry. Không hiển thị trạng thái giả. Lỗi: '+escapeHtml(error.message)+'</div>';
}finally{if(button){button.disabled=false;button.textContent='↻ Refresh registry';}}
}
function consoleView(){return header('OBSERVABILITY / 05','Developer Console','Logs, monitoring và integrations. Chưa có telemetry pipeline hoặc log stream kết nối.')+'<div class="notice">Không có log hệ thống thật được truy xuất. Dòng bên dưới là event trạng thái của giao diện preview.</div><div class="grid stats"><div class="stat"><div class="stat-top">Error rate</div><div class="stat-value">N/A</div><div class="stat-foot">No telemetry source</div></div><div class="stat"><div class="stat-top">P95 latency</div><div class="stat-value">N/A</div><div class="stat-foot">No request metrics</div></div><div class="stat"><div class="stat-top">Events</div><div class="stat-value">03</div><div class="stat-foot">Local preview events</div></div><div class="stat"><div class="stat-top">Integrations</div><div class="stat-value">0</div><div class="stat-foot">Not configured</div></div></div><div class="grid cols">'+panel('PREVIEW EVENT LOG','<div class="panel-body"><div class="log"><span>LOCAL</span><code>INFO</code><span>Control Center interface mounted</span></div><div class="log"><span>LOCAL</span><code>INFO</code><span>API catalog rendered</span></div><div class="log"><span>LOCAL</span><code>WARN</code><span>Backend telemetry adapter not configured</span></div><div class="log"><span>LOCAL</span><code>WARN</code><span>Authentication provider unavailable</span></div></div>','<small>LOCAL ONLY</small>')+panel('INTEGRATIONS','<div class="panel-body service-list">'+[['GitHub','Repository & CI status'],['Cloudflare','Workers / Pages'],['Vercel','Preview deployments'],['OpenTelemetry','Logs · metrics · traces'],['PostgreSQL / Redis','Persistence & cache']].map(x=>'<div class="service"><div><b>'+x[0]+'</b><small>'+x[1]+'</small></div><span class="state off">NOT CONNECTED</span></div>').join('')+'</div>')+'</div>'}
function docsView(){const docs=[['Getting Started','Tổng quan kiến trúc, yêu cầu runtime và cách khởi tạo môi trường.','/docs/getting-started'],['Server Architecture','Control plane, API layer, agent runtime và service adapters.','/docs/architecture'],['API Reference','Quy ước endpoint, request schema, auth và error response.','/docs/api'],['AI Agents','Provider configuration, agent lifecycle và orchestration.','/docs/agents'],['Authentication','OAuth, session management, account và access policy.','/docs/authentication'],['MCP Integration','MCP transport, initialize, tools/list và connection security.','/docs/mcp'],['Observability','Structured logging, metrics, tracing và alerting.','/docs/observability'],['Deployment','Environment variables, secrets, staging và production release.','/docs/deployment']];return header('KNOWLEDGE BASE / 06','Documentation','Tài liệu kỹ thuật và hướng dẫn tích hợp. Các trang con là cấu trúc đề xuất; nội dung chi tiết đang được xây dựng.')+'<div class="notice">Tài liệu trong danh mục này chưa được publish thành các trang riêng. Liên kết hiện mở repository để theo dõi source và cập nhật.</div><div class="doc-list">'+docs.map(d=>'<a class="doc" href="https://github.com/OCodejs/ocodejs.github.io" target="_blank" rel="noreferrer"><strong>'+d[0]+'</strong><p>'+d[1]+'</p><span>'+d[2]+' ↗</span></a>').join('')+'</div><div style="height:14px"></div>'+panel('PROJECT LINKS','<div class="panel-body feed"><a href="https://github.com/OCodejs" target="_blank" rel="noreferrer">OCode.js organization ↗</a><a href="https://github.com/OCodejs/ocodejs.github.io" target="_blank" rel="noreferrer">Control Center source ↗</a><a href="https://github.com/OCodejs/ocodejs.github.io/blob/main/docs/control-api-staging.md" target="_blank" rel="noreferrer">Control API staging guide ↗</a><a href="https://github.com/zskbot/ocodejs-cli" target="_blank" rel="noreferrer">OCode.js CLI ↗</a></div>')}
const renderers={overview,agents:agentView,api:apiView,auth:authView,mcp:mcpView,console:consoleView,docs:docsView,'service-registry':serviceRegistryView,providers:providersView,runtime:runtimeView};
function registerNavigationItem(item){
if(!item||typeof item.id!=='string'||!/^[a-z][a-z0-9-]*$/.test(item.id)||typeof item.label!=='string'||!item.label.trim())throw new TypeError('Navigation item requires a valid id and label');
const entry={id:item.id,label:item.label.trim(),icon:String(item.icon||'◇'),group:String(item.group||'MORE').trim()||'MORE',onSelect:typeof item.onSelect==='function'?item.onSelect:null};
const index=navigationRegistry.findIndex(existing=>existing.id===entry.id);
if(index>=0)navigationRegistry[index]=entry;else navigationRegistry.push(entry);
renderNavigation();
return {...entry};
}
function registerWorkspacePage(page){
if(!page||typeof page.render!=='function')throw new TypeError('Workspace page requires a render function');
const id=String(page.id||'');
if(!/^[a-z][a-z0-9-]*$/.test(id))throw new TypeError('Workspace page id is invalid');
names[id]=String(page.title||page.label||id);
renderers[id]=page.render;
return registerNavigationItem({id,label:names[id],icon:page.icon,group:page.group});
}
function renderNavigation(){
const root=document.getElementById('workspaceNavigation');
if(!root)return;
const groups=[...new Set(navigationRegistry.map(item=>item.group))];
root.innerHTML=groups.map(group=>'<div class="nav-group"><div class="nav-label">'+escapeHtml(group)+'</div>'+navigationRegistry.filter(item=>item.group===group).map(item=>'<button type="button" data-view="'+escapeHtml(item.id)+'" class="'+(item.id===current?'active':'')+'" aria-current="'+(item.id===current?'page':'false')+'"><span class="ico" aria-hidden="true">'+escapeHtml(item.icon)+'</span><span>'+escapeHtml(item.label)+'</span></button>').join('')+'</div>').join('');
}
window.OCodeNavigation=Object.freeze({
registerItem:registerNavigationItem,
registerPage:registerWorkspacePage,
getItems:()=>navigationRegistry.map(({onSelect,...item})=>({...item}))
});
function escapeHtml(v){return String(v).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
function navigate(key){if(!renderers[key])return;current=key;document.getElementById('crumb').textContent=names[key];renderNavigation();viewRoot.innerHTML=renderers[key]();document.getElementById('globalSearch').value='';setNavigationOpen(false);window.scrollTo({top:0,behavior:'smooth'});bindView();if(key==='overview')refreshDashboard();if(key==='agents')refreshAgentRegistry();if(key==='mcp')refreshMcpConnections();if(key==='auth')refreshAuthReadiness();if(key==='service-registry')refreshServiceRegistry();if(key==='providers')refreshProviders();if(key==='runtime')refreshRuntime()}
async function runMcpCheck(method){const output=document.getElementById('mcpResult'),status=document.getElementById('mcpStatus');if(!output||!status)return;output.textContent='Đang gửi '+method+'…';status.textContent='CHECKING';try{const response=await fetch(MCP_ENDPOINT,{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json, text/event-stream','MCP-Protocol-Version':'2025-03-26'},body:JSON.stringify({jsonrpc:'2.0',id:method==='initialize'?101:102,method,params:method==='initialize'?{protocolVersion:'2025-03-26',capabilities:{},clientInfo:{name:'ocodejs-control-center',version:'1.0.0'}}:{}})});const data=await response.json();if(!response.ok||data.error)throw new Error(data.error?.message||('HTTP '+response.status));if(method==='initialize'){status.textContent='INITIALIZE OK';output.textContent=JSON.stringify(data,null,2);await fetch(MCP_ENDPOINT,{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json, text/event-stream','MCP-Protocol-Version':'2025-03-26'},body:JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})});}else{const tools=data.result?.tools||[];status.textContent='TOOLS '+tools.length;output.textContent=tools.map(tool=>tool.name+' — '+tool.description).join('\n')||'No tools returned';}}catch(error){status.textContent='UNVERIFIED';output.textContent='MCP smoke test failed: '+error.message+'\nKiểm tra CORS, endpoint và trạng thái Worker.';}}
function bindView(){viewRoot.querySelectorAll('[data-go]').forEach(b=>b.addEventListener('click',()=>navigate(b.dataset.go)));const refresh=document.getElementById('refreshServices');if(refresh)refresh.addEventListener('click',refreshDashboard);const refreshAgents=document.getElementById('refreshAgents');if(refreshAgents)refreshAgents.addEventListener('click',refreshAgentRegistry);const refreshRegistry=document.getElementById('refreshServiceRegistry');if(refreshRegistry)refreshRegistry.addEventListener('click',refreshServiceRegistry);const refreshProvidersButton=document.getElementById('refreshProviders');if(refreshProvidersButton)refreshProvidersButton.addEventListener('click',refreshProviders);const refreshRuntimeButton=document.getElementById('refreshRuntime');if(refreshRuntimeButton)refreshRuntimeButton.addEventListener('click',refreshRuntime);const add=document.getElementById('addConnection')||document.getElementById('addConnectionEmpty');if(add)add.addEventListener('click',openModal);const refreshMcp=document.getElementById('refreshMcpConnections');if(refreshMcp)refreshMcp.addEventListener('click',refreshMcpConnections);const mcpInit=document.getElementById('mcpInitialize');if(mcpInit)mcpInit.addEventListener('click',()=>runMcpCheck('initialize'));const mcpTools=document.getElementById('mcpTools');if(mcpTools)mcpTools.addEventListener('click',()=>runMcpCheck('tools/list'));viewRoot.querySelectorAll('[data-connect]').forEach(b=>b.addEventListener('click',()=>{navigate('mcp');openModal();document.getElementById('connName').value=b.dataset.connect+' provider'}))}
function openModal(){document.getElementById('modal').classList.add('show');document.getElementById('connName').focus()}
function closeModal(){document.getElementById('modal').classList.remove('show')}
document.getElementById('workspaceNavigation').addEventListener('click',event=>{const button=event.target.closest('button[data-view]');if(!button)return;const item=navigationRegistry.find(entry=>entry.id===button.dataset.view);if(renderers[button.dataset.view])navigate(button.dataset.view);else if(item&&item.onSelect){item.onSelect();setNavigationOpen(false);}});
const sidebar=document.getElementById('sidebar'),menuButton=document.getElementById('mobileMenu'),navScrim=document.getElementById('navScrim');
function setNavigationOpen(open){sidebar.classList.toggle('open',open);sidebar.setAttribute('aria-hidden',String(!open));sidebar.inert=!open;document.body.classList.toggle('nav-open',open);menuButton.setAttribute('aria-expanded',String(open));menuButton.setAttribute('aria-label',open?'Đóng menu điều hướng':'Mở menu điều hướng');if(open){const first=sidebar.querySelector('.nav button');if(first)first.focus();}else menuButton.focus();}
menuButton.addEventListener('click',()=>setNavigationOpen(!sidebar.classList.contains('open')));
document.getElementById('closeNav').addEventListener('click',()=>setNavigationOpen(false));
navScrim.addEventListener('click',()=>setNavigationOpen(false));
document.addEventListener('keydown',event=>{if(event.key==='Escape'&&sidebar.classList.contains('open'))setNavigationOpen(false);});
document.getElementById('closeModal').addEventListener('click',closeModal);document.getElementById('cancelModal').addEventListener('click',closeModal);
document.getElementById('modal').addEventListener('click',e=>{if(e.target.id==='modal')closeModal()});
document.getElementById('connectionForm').addEventListener('submit',e=>{e.preventDefault();connections.push({name:document.getElementById('connName').value,type:document.getElementById('connType').value,url:document.getElementById('connUrl').value});closeModal();e.target.reset();navigate('mcp')});
document.getElementById('globalSearch').addEventListener('input',e=>{const q=e.target.value.toLowerCase();viewRoot.querySelectorAll('.service,.tile,.doc,.table tbody tr,.feed-item,.log').forEach(el=>el.style.display=el.textContent.toLowerCase().includes(q)?'':'none')});
renderNavigation();
navigate('overview');
</script>
</body>
</html>