Chaman1234 commited on
Commit
ce17688
·
verified ·
1 Parent(s): a35e733

Upload coding_lab_server.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. coding_lab_server.py +1337 -0
coding_lab_server.py ADDED
@@ -0,0 +1,1337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding_lab_server.py
2
+ # Antigravity Autonomous Coding Lab Server
3
+ # Powered by CAT V3 (Graph-MoE) & Ollama qwen2.5-coder:3b
4
+
5
+ import os
6
+ import sys
7
+ import json
8
+ import math
9
+ import urllib.parse
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ import threading
13
+
14
+ # Ensure workspace root is in python path
15
+ sys.path.append(str(Path(__file__).parent))
16
+
17
+ try:
18
+ import torch
19
+ from cat_v3.model import CATV3Model
20
+ from agent_executor import OllamaClient, SandboxExecutor, AutonomousCodingAgent
21
+ BACKEND_AVAILABLE = True
22
+ except ImportError:
23
+ BACKEND_AVAILABLE = False
24
+
25
+ _LOADED_SYSTEM = None
26
+
27
+ def load_system():
28
+ global _LOADED_SYSTEM
29
+ if _LOADED_SYSTEM is not None:
30
+ return _LOADED_SYSTEM
31
+
32
+ if not BACKEND_AVAILABLE:
33
+ print("Backend dependencies not available.")
34
+ return None
35
+
36
+ checkpoint_path = "checkpoints/cat_v3/cat_v3_model.pt"
37
+ if not os.path.exists(checkpoint_path):
38
+ print(f"Checkpoint {checkpoint_path} not found. Run training first.")
39
+ return None
40
+
41
+ try:
42
+ device = "cpu"
43
+ checkpoint = torch.load(checkpoint_path, map_location=device)
44
+ vocab = checkpoint["vocab"]
45
+ tokenizer = checkpoint["tokenizer"]
46
+ expert_graphs = checkpoint["expert_graphs"]
47
+
48
+ model = CATV3Model(
49
+ num_concepts=vocab.size(),
50
+ tokenizer_vocab_size=tokenizer.vocab_size(),
51
+ pad_id=tokenizer.pad_id,
52
+ eos_id=tokenizer.eos_id,
53
+ expert_graphs=expert_graphs,
54
+ concept_dim=128,
55
+ hidden_size=128,
56
+ path_length=8,
57
+ top_m=8,
58
+ decoder_vocab_size=tokenizer.vocab_size()
59
+ ).to(device)
60
+ model.load_state_dict(checkpoint["model_state_dict"])
61
+ model.eval()
62
+
63
+ _LOADED_SYSTEM = {
64
+ "model": model,
65
+ "vocab": vocab,
66
+ "tokenizer": tokenizer,
67
+ "expert_graphs": expert_graphs,
68
+ "device": device
69
+ }
70
+ print("CAT V3 model loaded successfully for Coding Lab.")
71
+ return _LOADED_SYSTEM
72
+ except Exception as e:
73
+ print(f"Error loading CAT V3 model: {e}")
74
+ return None
75
+
76
+ def predict_v3_routing(question):
77
+ loaded = load_system()
78
+ if not loaded:
79
+ # Fallback simulated routing if no checkpoint
80
+ return {
81
+ "reasoning_path": ["data_input", "sort", "syntax", "control_flow"],
82
+ "activated_domains": ["coding", "mathematics"],
83
+ "domain_probabilities": {
84
+ "mechanical": 0.05, "civil": 0.05, "electrical": 0.02,
85
+ "physics": 0.08, "mathematics": 0.72, "english": 0.12, "coding": 0.95
86
+ },
87
+ "nodes": [{"name": "syntax", "activation": 0.8}, {"name": "sort", "activation": 0.9}],
88
+ "edges": []
89
+ }
90
+
91
+ model = loaded["model"]
92
+ vocab = loaded["vocab"]
93
+ tokenizer = loaded["tokenizer"]
94
+ device = loaded["device"]
95
+
96
+ DOMAINS_LIST = ["mechanical", "civil", "electrical", "physics", "mathematics", "english", "coding"]
97
+
98
+ with torch.no_grad():
99
+ input_ids, attention_mask = tokenizer.encode(question, max_length=32)
100
+ input_ids = input_ids.unsqueeze(0).to(device)
101
+ attention_mask = attention_mask.unsqueeze(0).to(device)
102
+
103
+ outputs = model.generate_response(
104
+ input_ids=input_ids,
105
+ attention_mask=attention_mask,
106
+ router_top_k=2,
107
+ router_threshold=0.4
108
+ )
109
+
110
+ router_probs = outputs["router_probs"][0].cpu().tolist()
111
+ active_mask = outputs["router_mask"][0].cpu().tolist()
112
+
113
+ activated_domains = [DOMAINS_LIST[i] for i, mask in enumerate(active_mask) if mask]
114
+ domain_probs = {DOMAINS_LIST[i]: prob for i, prob in enumerate(router_probs)}
115
+
116
+ fusion_report = model.fusion.get_symbolic_report(
117
+ vocab=vocab,
118
+ expert_reports=outputs["expert_reports"],
119
+ router_mask=outputs["router_mask"],
120
+ domain_names=DOMAINS_LIST
121
+ )[0]
122
+
123
+ reasoning_path = []
124
+ if fusion_report["reasoning_paths"]:
125
+ reasoning_path = fusion_report["reasoning_paths"][0]
126
+ else:
127
+ # Fallback path if empty
128
+ reasoning_path = ["data_input", "syntax", "control_flow"]
129
+
130
+ nodes_list = []
131
+ for name in vocab.concepts:
132
+ if name not in ("<PAD>", "<EOS>"):
133
+ act = 0.95 if name in fusion_report["concepts"] else 0.05
134
+ nodes_list.append({
135
+ "name": name,
136
+ "activation": act
137
+ })
138
+
139
+ edges_list = []
140
+ for d_idx, d_name in enumerate(DOMAINS_LIST):
141
+ if active_mask[d_idx]:
142
+ expert = model.experts[d_name]
143
+ edge_index = expert.edge_index.cpu()
144
+ for i in range(edge_index.size(1)):
145
+ u = vocab.id_to_concept[edge_index[0, i].item()]
146
+ v = vocab.id_to_concept[edge_index[1, i].item()]
147
+ if u not in ("<PAD>", "<EOS>") and v not in ("<PAD>", "<EOS>"):
148
+ edges_list.append({
149
+ "from": u,
150
+ "to": v,
151
+ "weight": 1.0
152
+ })
153
+
154
+ return {
155
+ "reasoning_path": reasoning_path,
156
+ "activated_domains": activated_domains,
157
+ "domain_probabilities": domain_probs,
158
+ "nodes": nodes_list,
159
+ "edges": edges_list
160
+ }
161
+
162
+ class CodingLabRequestHandler(BaseHTTPRequestHandler):
163
+ def log_message(self, format, *args):
164
+ pass
165
+
166
+ def do_GET(self):
167
+ parsed = urllib.parse.urlparse(self.path)
168
+ if parsed.path == "/" or parsed.path == "/index.html":
169
+ self.send_response(200)
170
+ self.send_header("Content-Type", "text/html; charset=utf-8")
171
+ self.end_headers()
172
+ self.wfile.write(LAB_HTML.encode("utf-8"))
173
+ elif parsed.path == "/api/status":
174
+ ollama = OllamaClient()
175
+ conn_ok, conn_msg = ollama.check_connection()
176
+ runtimes = SandboxExecutor.get_supported_runtimes()
177
+
178
+ status_data = {
179
+ "ollama_connected": conn_ok,
180
+ "ollama_message": conn_msg,
181
+ "runtimes": runtimes,
182
+ "cat_v3_loaded": load_system() is not None
183
+ }
184
+ self.send_response(200)
185
+ self.send_header("Content-Type", "application/json")
186
+ self.end_headers()
187
+ self.wfile.write(json.dumps(status_data).encode("utf-8"))
188
+ elif parsed.path == "/api/agent/run":
189
+ query_params = urllib.parse.parse_qs(parsed.query)
190
+ question = query_params.get("question", [""])[0].strip()
191
+ language = query_params.get("language", ["python"])[0].strip().lower()
192
+ max_iterations = int(query_params.get("max_iterations", ["3"])[0])
193
+ temperature = float(query_params.get("temperature", ["0.2"])[0])
194
+
195
+ try:
196
+ if not question:
197
+ raise ValueError("Question cannot be empty.")
198
+
199
+ # Set headers for Server-Sent Events (SSE)
200
+ self.send_response(200)
201
+ self.send_header("Content-Type", "text/event-stream")
202
+ self.send_header("Cache-Control", "no-cache")
203
+ self.send_header("Connection", "keep-alive")
204
+ self.send_header("Access-Control-Allow-Origin", "*")
205
+ self.end_headers()
206
+
207
+ def send_event(event_type, payload):
208
+ event_data = {"event": event_type, "data": payload}
209
+ try:
210
+ self.wfile.write(f"data: {json.dumps(event_data)}\n\n".encode("utf-8"))
211
+ self.wfile.flush()
212
+ except Exception:
213
+ pass # Connection closed
214
+
215
+ # Step 1: Run CAT V3 Routing
216
+ send_event("status", "Running query through CAT V3 Graph-MoE router...")
217
+ routing_res = predict_v3_routing(question)
218
+
219
+ send_event("routing", {
220
+ "reasoning_path": routing_res["reasoning_path"],
221
+ "activated_domains": routing_res["activated_domains"],
222
+ "domain_probabilities": routing_res["domain_probabilities"],
223
+ "nodes": routing_res["nodes"],
224
+ "edges": routing_res["edges"]
225
+ })
226
+
227
+ # Step 2: Initialize Agent
228
+ ollama = OllamaClient(model="qwen2.5-coder:3b")
229
+ conn_ok, conn_msg = ollama.check_connection()
230
+ if not conn_ok:
231
+ send_event("error", f"Ollama Error: {conn_msg}")
232
+ return
233
+
234
+ sandbox = SandboxExecutor()
235
+ agent = AutonomousCodingAgent(ollama, sandbox)
236
+
237
+ def agent_callback(msg):
238
+ # Direct forwarding of callback logs to SSE client
239
+ send_event("agent_log", msg)
240
+
241
+ # Step 3: Run the loop
242
+ run_res = agent.run_agent_loop(
243
+ task=question,
244
+ language=language,
245
+ concept_path=routing_res["reasoning_path"],
246
+ max_iterations=max_iterations,
247
+ callback=agent_callback
248
+ )
249
+
250
+ # Step 4: Finished
251
+ send_event("done", run_res)
252
+
253
+ except Exception as e:
254
+ import traceback
255
+ traceback.print_exc()
256
+ try:
257
+ self.send_response(500)
258
+ self.send_header("Content-Type", "application/json")
259
+ self.end_headers()
260
+ self.wfile.write(json.dumps({"error": str(e)}).encode("utf-8"))
261
+ except Exception:
262
+ pass
263
+ else:
264
+ self.send_response(404)
265
+ self.end_headers()
266
+
267
+ def do_POST(self):
268
+ parsed = urllib.parse.urlparse(self.path)
269
+ if parsed.path == "/api/agent/run":
270
+ content_length = int(self.headers.get("Content-Length", 0))
271
+ body = self.rfile.read(content_length)
272
+
273
+ try:
274
+ data = json.loads(body.decode("utf-8"))
275
+ question = data.get("question", "").strip()
276
+ language = data.get("language", "python").strip().lower()
277
+ max_iterations = int(data.get("max_iterations", 3))
278
+ temperature = float(data.get("temperature", 0.2))
279
+
280
+ if not question:
281
+ raise ValueError("Question cannot be empty.")
282
+
283
+ # Set headers for Server-Sent Events (SSE)
284
+ self.send_response(200)
285
+ self.send_header("Content-Type", "text/event-stream")
286
+ self.send_header("Cache-Control", "no-cache")
287
+ self.send_header("Connection", "keep-alive")
288
+ self.send_header("Access-Control-Allow-Origin", "*")
289
+ self.end_headers()
290
+
291
+ def send_event(event_type, payload):
292
+ event_data = {"event": event_type, "data": payload}
293
+ try:
294
+ self.wfile.write(f"data: {json.dumps(event_data)}\n\n".encode("utf-8"))
295
+ self.wfile.flush()
296
+ except Exception:
297
+ pass # Connection closed
298
+
299
+ # Step 1: Run CAT V3 Routing
300
+ send_event("status", "Running query through CAT V3 Graph-MoE router...")
301
+ routing_res = predict_v3_routing(question)
302
+
303
+ send_event("routing", {
304
+ "reasoning_path": routing_res["reasoning_path"],
305
+ "activated_domains": routing_res["activated_domains"],
306
+ "domain_probabilities": routing_res["domain_probabilities"],
307
+ "nodes": routing_res["nodes"],
308
+ "edges": routing_res["edges"]
309
+ })
310
+
311
+ # Step 2: Initialize Agent
312
+ ollama = OllamaClient(model="qwen2.5-coder:3b")
313
+ conn_ok, conn_msg = ollama.check_connection()
314
+ if not conn_ok:
315
+ send_event("error", f"Ollama Error: {conn_msg}")
316
+ return
317
+
318
+ sandbox = SandboxExecutor()
319
+ agent = AutonomousCodingAgent(ollama, sandbox)
320
+
321
+ def agent_callback(msg):
322
+ # Direct forwarding of callback logs to SSE client
323
+ send_event("agent_log", msg)
324
+
325
+ # Step 3: Run the loop
326
+ run_res = agent.run_agent_loop(
327
+ task=question,
328
+ language=language,
329
+ concept_path=routing_res["reasoning_path"],
330
+ max_iterations=max_iterations,
331
+ callback=agent_callback
332
+ )
333
+
334
+ # Step 4: Finished
335
+ send_event("done", run_res)
336
+
337
+ except Exception as e:
338
+ import traceback
339
+ traceback.print_exc()
340
+ try:
341
+ self.send_response(500)
342
+ self.send_header("Content-Type", "application/json")
343
+ self.end_headers()
344
+ self.wfile.write(json.dumps({"error": str(e)}).encode("utf-8"))
345
+ except Exception:
346
+ pass
347
+ else:
348
+ self.send_response(404)
349
+ self.end_headers()
350
+
351
+ # ─── FRONTEND HTML / CSS / JS ───────────────────────────────────────────────
352
+
353
+ LAB_HTML = r"""<!DOCTYPE html>
354
+ <html lang="en">
355
+ <head>
356
+ <meta charset="UTF-8">
357
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
358
+ <title>Antigravity Autonomous Coding Lab</title>
359
+ <meta name="description" content="State of the art multi-language autonomous coding agent visual interface.">
360
+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Fira+Code:wght@400;500;600&display=swap" rel="stylesheet">
361
+ <script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
362
+ <style>
363
+ :root {
364
+ --bg-deep: #05070a;
365
+ --bg-base: #0a0d14;
366
+ --bg-surface: #101422;
367
+ --bg-elevated: #161c30;
368
+ --bg-glass: rgba(10, 13, 20, 0.75);
369
+
370
+ --border-glow: rgba(99, 102, 241, 0.25);
371
+ --border-subtle: rgba(255, 255, 255, 0.06);
372
+ --border-medium: rgba(255, 255, 255, 0.15);
373
+
374
+ --text-primary: #f8fafc;
375
+ --text-secondary: #94a3b8;
376
+ --text-muted: #475569;
377
+
378
+ --accent-primary: #6366f1;
379
+ --accent-glow: rgba(99, 102, 241, 0.15);
380
+ --accent-green: #10b981;
381
+ --accent-amber: #f59e0b;
382
+ --accent-rose: #f43f5e;
383
+ --accent-cyan: #06b6d4;
384
+
385
+ --font-main: 'Outfit', sans-serif;
386
+ --font-code: 'Fira Code', monospace;
387
+ --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.5);
388
+ --radius-md: 12px;
389
+ --radius-lg: 16px;
390
+ }
391
+
392
+ * {
393
+ box-sizing: border-box;
394
+ margin: 0;
395
+ padding: 0;
396
+ }
397
+
398
+ body {
399
+ font-family: var(--font-main);
400
+ background: var(--bg-deep);
401
+ color: var(--text-primary);
402
+ height: 100vh;
403
+ display: flex;
404
+ flex-direction: column;
405
+ overflow: hidden;
406
+ }
407
+
408
+ body::before {
409
+ content: '';
410
+ position: fixed;
411
+ top: 0;
412
+ left: 20%;
413
+ width: 60%;
414
+ height: 40%;
415
+ background: radial-gradient(ellipse at center, rgba(99, 102, 241, 0.08) 0%, transparent 70%);
416
+ pointer-events: none;
417
+ z-index: 0;
418
+ }
419
+
420
+ header {
421
+ height: 70px;
422
+ background: var(--bg-base);
423
+ border-bottom: 1px solid var(--border-subtle);
424
+ display: flex;
425
+ align-items: center;
426
+ justify-content: justify;
427
+ padding: 0 2rem;
428
+ position: relative;
429
+ z-index: 10;
430
+ backdrop-filter: blur(10px);
431
+ }
432
+
433
+ .header-left {
434
+ display: flex;
435
+ align-items: center;
436
+ gap: 1rem;
437
+ }
438
+
439
+ .logo {
440
+ width: 42px;
441
+ height: 42px;
442
+ background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
443
+ border-radius: var(--radius-md);
444
+ display: flex;
445
+ align-items: center;
446
+ justify-content: center;
447
+ font-size: 1.3rem;
448
+ font-weight: 800;
449
+ color: #fff;
450
+ box-shadow: 0 0 15px rgba(99,102,241,0.4);
451
+ }
452
+
453
+ .title-group h1 {
454
+ font-size: 1.15rem;
455
+ font-weight: 700;
456
+ letter-spacing: -0.3px;
457
+ }
458
+
459
+ .title-group p {
460
+ font-size: 0.75rem;
461
+ color: var(--text-secondary);
462
+ }
463
+
464
+ .header-status {
465
+ display: flex;
466
+ align-items: center;
467
+ gap: 1.5rem;
468
+ }
469
+
470
+ .status-pill {
471
+ display: flex;
472
+ align-items: center;
473
+ gap: 0.5rem;
474
+ padding: 0.4rem 0.8rem;
475
+ background: rgba(16, 185, 129, 0.08);
476
+ border: 1px solid rgba(16, 185, 129, 0.2);
477
+ border-radius: 999px;
478
+ font-size: 0.72rem;
479
+ font-weight: 600;
480
+ color: var(--accent-green);
481
+ }
482
+
483
+ .status-dot {
484
+ width: 6px;
485
+ height: 6px;
486
+ background: var(--accent-green);
487
+ border-radius: 50%;
488
+ animation: pulse 2s infinite;
489
+ }
490
+
491
+ @keyframes pulse {
492
+ 0%, 100% { opacity: 1; }
493
+ 50% { opacity: 0.3; }
494
+ }
495
+
496
+ #main-container {
497
+ flex: 1;
498
+ display: grid;
499
+ grid-template-columns: 360px 1fr 1fr;
500
+ overflow: hidden;
501
+ position: relative;
502
+ z-index: 1;
503
+ }
504
+
505
+ /* Panels layout */
506
+ .panel {
507
+ display: flex;
508
+ flex-direction: column;
509
+ border-right: 1px solid var(--border-subtle);
510
+ background: var(--bg-base);
511
+ overflow: hidden;
512
+ }
513
+
514
+ .panel:last-child {
515
+ border-right: none;
516
+ }
517
+
518
+ .panel-header {
519
+ padding: 1.2rem;
520
+ border-bottom: 1px solid var(--border-subtle);
521
+ display: flex;
522
+ align-items: center;
523
+ justify-content: space-between;
524
+ }
525
+
526
+ .panel-header h2 {
527
+ font-size: 0.9rem;
528
+ font-weight: 600;
529
+ letter-spacing: 0.5px;
530
+ text-transform: uppercase;
531
+ color: var(--text-secondary);
532
+ }
533
+
534
+ .panel-body {
535
+ flex: 1;
536
+ padding: 1.5rem;
537
+ overflow-y: auto;
538
+ display: flex;
539
+ flex-direction: column;
540
+ gap: 1.5rem;
541
+ }
542
+
543
+ /* Controls Form */
544
+ .form-group {
545
+ display: flex;
546
+ flex-direction: column;
547
+ gap: 0.5rem;
548
+ }
549
+
550
+ .form-group label {
551
+ font-size: 0.8rem;
552
+ font-weight: 600;
553
+ color: var(--text-secondary);
554
+ }
555
+
556
+ textarea {
557
+ width: 100%;
558
+ height: 120px;
559
+ background: var(--bg-surface);
560
+ border: 1px solid var(--border-subtle);
561
+ border-radius: var(--radius-md);
562
+ padding: 0.8rem;
563
+ color: var(--text-primary);
564
+ font-family: inherit;
565
+ font-size: 0.85rem;
566
+ resize: none;
567
+ outline: none;
568
+ transition: border-color 0.2s;
569
+ }
570
+
571
+ textarea:focus {
572
+ border-color: var(--accent-primary);
573
+ box-shadow: 0 0 10px rgba(99,102,241,0.1);
574
+ }
575
+
576
+ select {
577
+ width: 100%;
578
+ background: var(--bg-surface);
579
+ border: 1px solid var(--border-subtle);
580
+ border-radius: var(--radius-md);
581
+ padding: 0.8rem;
582
+ color: var(--text-primary);
583
+ font-family: inherit;
584
+ font-size: 0.85rem;
585
+ outline: none;
586
+ cursor: pointer;
587
+ }
588
+
589
+ .slider-group {
590
+ display: flex;
591
+ align-items: center;
592
+ justify-content: space-between;
593
+ font-size: 0.85rem;
594
+ }
595
+
596
+ .slider-group input {
597
+ flex: 1;
598
+ margin-left: 1rem;
599
+ accent-color: var(--accent-primary);
600
+ }
601
+
602
+ .btn-run {
603
+ width: 100%;
604
+ padding: 1rem;
605
+ background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
606
+ border: none;
607
+ border-radius: var(--radius-md);
608
+ color: #fff;
609
+ font-family: var(--font-main);
610
+ font-weight: 700;
611
+ font-size: 0.95rem;
612
+ cursor: pointer;
613
+ transition: transform 0.1s, box-shadow 0.2s;
614
+ box-shadow: 0 4px 15px rgba(99,102,241,0.3);
615
+ display: flex;
616
+ align-items: center;
617
+ justify-content: center;
618
+ gap: 0.5rem;
619
+ }
620
+
621
+ .btn-run:hover {
622
+ box-shadow: 0 6px 20px rgba(99,102,241,0.45);
623
+ }
624
+
625
+ .btn-run:active {
626
+ transform: scale(0.98);
627
+ }
628
+
629
+ .btn-run:disabled {
630
+ background: var(--bg-elevated);
631
+ color: var(--text-secondary);
632
+ cursor: not-allowed;
633
+ box-shadow: none;
634
+ }
635
+
636
+ /* Compiler check table */
637
+ .system-check-card {
638
+ background: var(--bg-surface);
639
+ border: 1px solid var(--border-subtle);
640
+ border-radius: var(--radius-md);
641
+ padding: 1rem;
642
+ }
643
+
644
+ .system-check-card h3 {
645
+ font-size: 0.78rem;
646
+ text-transform: uppercase;
647
+ letter-spacing: 0.5px;
648
+ color: var(--text-secondary);
649
+ margin-bottom: 0.8rem;
650
+ }
651
+
652
+ .compiler-row {
653
+ display: flex;
654
+ align-items: center;
655
+ justify-content: space-between;
656
+ font-size: 0.78rem;
657
+ padding: 0.4rem 0;
658
+ border-bottom: 1px solid rgba(255,255,255,0.03);
659
+ }
660
+
661
+ .compiler-row:last-child {
662
+ border-bottom: none;
663
+ }
664
+
665
+ .badge-ok {
666
+ color: var(--accent-green);
667
+ font-weight: 600;
668
+ }
669
+
670
+ .badge-warn {
671
+ color: var(--accent-amber);
672
+ font-weight: 600;
673
+ }
674
+
675
+ /* Visualizer Panel (Middle) */
676
+ #network-canvas {
677
+ flex: 1;
678
+ background: #07090f;
679
+ position: relative;
680
+ }
681
+
682
+ .router-bars {
683
+ height: 150px;
684
+ border-top: 1px solid var(--border-subtle);
685
+ background: var(--bg-surface);
686
+ padding: 1rem;
687
+ display: flex;
688
+ flex-direction: column;
689
+ gap: 0.4rem;
690
+ overflow-y: auto;
691
+ }
692
+
693
+ .router-bars h3 {
694
+ font-size: 0.75rem;
695
+ text-transform: uppercase;
696
+ color: var(--text-secondary);
697
+ margin-bottom: 0.3rem;
698
+ }
699
+
700
+ .bar-row {
701
+ display: flex;
702
+ align-items: center;
703
+ font-size: 0.7rem;
704
+ gap: 0.5rem;
705
+ }
706
+
707
+ .bar-label {
708
+ width: 80px;
709
+ text-align: right;
710
+ font-weight: 600;
711
+ }
712
+
713
+ .bar-container {
714
+ flex: 1;
715
+ height: 8px;
716
+ background: rgba(255,255,255,0.05);
717
+ border-radius: 4px;
718
+ overflow: hidden;
719
+ }
720
+
721
+ .bar-fill {
722
+ height: 100%;
723
+ background: var(--accent-primary);
724
+ width: 0%;
725
+ transition: width 0.4s ease-out;
726
+ border-radius: 4px;
727
+ }
728
+
729
+ .bar-val {
730
+ width: 35px;
731
+ text-align: left;
732
+ font-weight: 500;
733
+ }
734
+
735
+ /* Code/Logs Panel (Right) */
736
+ .tabs-header {
737
+ display: flex;
738
+ border-bottom: 1px solid var(--border-subtle);
739
+ background: var(--bg-surface);
740
+ }
741
+
742
+ .tab-btn {
743
+ flex: 1;
744
+ padding: 1rem 0;
745
+ background: none;
746
+ border: none;
747
+ border-bottom: 2px solid transparent;
748
+ color: var(--text-secondary);
749
+ font-family: var(--font-main);
750
+ font-weight: 600;
751
+ font-size: 0.85rem;
752
+ cursor: pointer;
753
+ transition: all 0.2s;
754
+ }
755
+
756
+ .tab-btn:hover {
757
+ color: var(--text-primary);
758
+ background: rgba(255,255,255,0.02);
759
+ }
760
+
761
+ .tab-btn.active {
762
+ color: var(--accent-primary);
763
+ border-bottom-color: var(--accent-primary);
764
+ background: rgba(99,102,241,0.03);
765
+ }
766
+
767
+ .tab-content {
768
+ flex: 1;
769
+ display: none;
770
+ padding: 1.2rem;
771
+ background: #080b12;
772
+ overflow: auto;
773
+ position: relative;
774
+ }
775
+
776
+ .tab-content.active {
777
+ display: block;
778
+ }
779
+
780
+ /* Logging Terminal */
781
+ .terminal-log {
782
+ font-family: var(--font-code);
783
+ font-size: 0.78rem;
784
+ line-height: 1.5;
785
+ color: #d1d5db;
786
+ }
787
+
788
+ .log-entry {
789
+ margin-bottom: 0.8rem;
790
+ padding-bottom: 0.6rem;
791
+ border-bottom: 1px solid rgba(255,255,255,0.02);
792
+ }
793
+
794
+ .log-time {
795
+ color: var(--text-muted);
796
+ margin-right: 0.5rem;
797
+ }
798
+
799
+ .log-tag {
800
+ font-weight: 700;
801
+ padding: 0.1rem 0.4rem;
802
+ border-radius: 4px;
803
+ font-size: 0.68rem;
804
+ margin-right: 0.5rem;
805
+ }
806
+
807
+ .tag-status { background: rgba(99,102,241,0.15); color: var(--accent-primary); }
808
+ .tag-thought { background: rgba(6,182,212,0.15); color: var(--accent-cyan); }
809
+ .tag-code { background: rgba(245,158,11,0.15); color: var(--accent-amber); }
810
+ .tag-execution { background: rgba(16,185,129,0.15); color: var(--accent-green); }
811
+ .tag-error { background: rgba(244,63,94,0.15); color: var(--accent-rose); }
812
+
813
+ pre {
814
+ background: rgba(0,0,0,0.3);
815
+ border: 1px solid var(--border-subtle);
816
+ border-radius: 6px;
817
+ padding: 0.8rem;
818
+ margin-top: 0.4rem;
819
+ overflow-x: auto;
820
+ font-family: var(--font-code);
821
+ color: #f1f5f9;
822
+ }
823
+
824
+ .code-container {
825
+ height: 100%;
826
+ display: flex;
827
+ flex-direction: column;
828
+ gap: 1rem;
829
+ }
830
+
831
+ .code-pre {
832
+ flex: 1;
833
+ background: #020408;
834
+ border: 1px solid var(--border-subtle);
835
+ border-radius: 8px;
836
+ padding: 1.2rem;
837
+ font-family: var(--font-code);
838
+ font-size: 0.85rem;
839
+ color: #e2e8f0;
840
+ white-space: pre-wrap;
841
+ overflow-y: auto;
842
+ position: relative;
843
+ }
844
+
845
+ .copy-btn {
846
+ position: absolute;
847
+ top: 1rem;
848
+ right: 1rem;
849
+ padding: 0.4rem 0.8rem;
850
+ background: var(--bg-elevated);
851
+ border: 1px solid var(--border-subtle);
852
+ border-radius: 4px;
853
+ color: var(--text-primary);
854
+ font-family: var(--font-main);
855
+ font-size: 0.72rem;
856
+ font-weight: 600;
857
+ cursor: pointer;
858
+ transition: all 0.2s;
859
+ }
860
+
861
+ .copy-btn:hover {
862
+ background: var(--accent-primary);
863
+ border-color: var(--accent-primary);
864
+ }
865
+
866
+ /* Spinner */
867
+ .spinner {
868
+ width: 16px;
869
+ height: 16px;
870
+ border: 2px solid rgba(255,255,255,0.3);
871
+ border-top-color: #fff;
872
+ border-radius: 50%;
873
+ animation: spin 0.8s linear infinite;
874
+ display: inline-block;
875
+ }
876
+
877
+ @keyframes spin {
878
+ to { transform: rotate(360deg); }
879
+ }
880
+ </style>
881
+ </head>
882
+ <body>
883
+
884
+ <header>
885
+ <div class="header-left">
886
+ <div class="logo">Ag</div>
887
+ <div class="title-group">
888
+ <h1>Antigravity Coding Lab</h1>
889
+ <p>CAT V3 (Graph-MoE) + Ollama qwen2.5-coder:3b Autonomous Agent Loop</p>
890
+ </div>
891
+ </div>
892
+ <div class="header-status">
893
+ <div class="status-pill" id="ollama-status">
894
+ <div class="status-dot"></div>
895
+ Ollama: Checking...
896
+ </div>
897
+ <div class="status-pill" id="cat-status" style="background: rgba(99,102,241,0.08); border-color: rgba(99,102,241,0.2); color: var(--accent-primary);">
898
+ <div class="status-dot" style="background: var(--accent-primary);"></div>
899
+ Model: Checking...
900
+ </div>
901
+ </div>
902
+ </header>
903
+
904
+ <div id="main-container">
905
+
906
+ <!-- Controls Panel -->
907
+ <div class="panel">
908
+ <div class="panel-header">
909
+ <h2>Configuration</h2>
910
+ </div>
911
+ <div class="panel-body">
912
+ <div class="form-group">
913
+ <label for="prompt-input">Coding Task</label>
914
+ <textarea id="prompt-input" placeholder="e.g. Write a script to calculate fibonacci values recursively."></textarea>
915
+ </div>
916
+
917
+ <div class="form-group">
918
+ <label for="lang-select">Programming Language</label>
919
+ <select id="lang-select">
920
+ <option value="python">Python</option>
921
+ <option value="javascript">JavaScript (Node.js)</option>
922
+ <option value="cpp">C++</option>
923
+ <option value="go">Go</option>
924
+ <option value="sql">SQL (SQLite3)</option>
925
+ <option value="html">HTML/CSS (Validator)</option>
926
+ <option value="java">Java</option>
927
+ <option value="rust">Rust</option>
928
+ </select>
929
+ </div>
930
+
931
+ <div class="form-group">
932
+ <div class="slider-group">
933
+ <label for="temp-slider">Temperature</label>
934
+ <span id="temp-val">0.2</span>
935
+ </div>
936
+ <input type="range" id="temp-slider" min="0.1" max="1.0" step="0.05" value="0.2" oninput="document.getElementById('temp-val').innerText = this.value">
937
+ </div>
938
+
939
+ <div class="form-group">
940
+ <div class="slider-group">
941
+ <label for="iter-slider">Max Debug Retries</label>
942
+ <span id="iter-val">3</span>
943
+ </div>
944
+ <input type="range" id="iter-slider" min="1" max="5" step="1" value="3" oninput="document.getElementById('iter-val').innerText = this.value">
945
+ </div>
946
+
947
+ <button class="btn-run" id="btn-execute">
948
+ <span>Run Coding Agent</span>
949
+ </button>
950
+
951
+ <div class="system-check-card">
952
+ <h3>Runtime Diagnostics</h3>
953
+ <div id="diagnostics-list">
954
+ <!-- Filled by JS -->
955
+ </div>
956
+ </div>
957
+ </div>
958
+ </div>
959
+
960
+ <!-- Visualizer Panel -->
961
+ <div class="panel">
962
+ <div class="panel-header">
963
+ <h2>Concept Planning Graph (CAT V3)</h2>
964
+ </div>
965
+ <div id="network-canvas"></div>
966
+
967
+ <div class="router-bars">
968
+ <h3>MoE Routing Probabilities</h3>
969
+ <div id="routing-bars-list">
970
+ <!-- Bars filled dynamically -->
971
+ </div>
972
+ </div>
973
+ </div>
974
+
975
+ <!-- Outputs Panel -->
976
+ <div class="panel">
977
+ <div class="tabs-header">
978
+ <button class="tab-btn active" onclick="switchTab('trace')">Execution Trace</button>
979
+ <button class="tab-btn" onclick="switchTab('code')">Generated Code</button>
980
+ <button class="tab-btn" onclick="switchTab('stdout')">Stdout Output</button>
981
+ </div>
982
+
983
+ <!-- Trace content -->
984
+ <div class="tab-content active" id="tab-trace">
985
+ <div class="terminal-log" id="log-container">
986
+ <div class="log-entry"><span class="log-time">00:00:00</span><span class="log-tag tag-status">System</span>Agent ready. Enter task details and click run.</div>
987
+ </div>
988
+ </div>
989
+
990
+ <!-- Code Content -->
991
+ <div class="tab-content" id="tab-code">
992
+ <div class="code-container">
993
+ <div class="code-pre" id="code-output">
994
+ <button class="copy-btn" onclick="copyGeneratedCode()">Copy</button>
995
+ <code id="code-content">// Code will be shown here...</code>
996
+ </div>
997
+ </div>
998
+ </div>
999
+
1000
+ <!-- Output Content -->
1001
+ <div class="tab-content" id="tab-stdout">
1002
+ <pre id="stdout-output">Execution stdout/stderr output will be displayed here...</pre>
1003
+ </div>
1004
+ </div>
1005
+
1006
+ </div>
1007
+
1008
+ <script>
1009
+ let network = null;
1010
+ let activeEventSource = null;
1011
+
1012
+ // Initialize Diagnostics and Status
1013
+ async function fetchStatus() {
1014
+ try {
1015
+ const response = await fetch('/api/status');
1016
+ const data = await response.json();
1017
+
1018
+ // Update Ollama status badge
1019
+ const ollamaPill = document.getElementById('ollama-status');
1020
+ if (data.ollama_connected) {
1021
+ ollamaPill.innerHTML = '<div class="status-dot"></div>Ollama: Online';
1022
+ ollamaPill.style.background = 'rgba(16, 185, 129, 0.08)';
1023
+ ollamaPill.style.color = 'var(--accent-green)';
1024
+ } else {
1025
+ ollamaPill.innerHTML = '<div class="status-dot" style="background: var(--accent-rose);"></div>Ollama: Offline';
1026
+ ollamaPill.style.background = 'rgba(244, 63, 94, 0.08)';
1027
+ ollamaPill.style.color = 'var(--accent-rose)';
1028
+ }
1029
+
1030
+ // Update CAT V3 badge
1031
+ const catPill = document.getElementById('cat-status');
1032
+ if (data.cat_v3_loaded) {
1033
+ catPill.innerHTML = '<div class="status-dot"></div>CAT V3: Ready';
1034
+ catPill.style.background = 'rgba(99, 102, 241, 0.08)';
1035
+ catPill.style.color = 'var(--accent-primary)';
1036
+ } else {
1037
+ catPill.innerHTML = '<div class="status-dot" style="background: var(--accent-amber);"></div>CAT V3: Simulated';
1038
+ catPill.style.background = 'rgba(245, 158, 11, 0.08)';
1039
+ catPill.style.color = 'var(--accent-amber)';
1040
+ }
1041
+
1042
+ // Fill compiler rows
1043
+ const diagList = document.getElementById('diagnostics-list');
1044
+ diagList.innerHTML = '';
1045
+ for (const [lang, ok] of Object.entries(data.runtimes)) {
1046
+ const row = document.createElement('div');
1047
+ row.className = 'compiler-row';
1048
+ row.innerHTML = `
1049
+ <span>${lang.toUpperCase()}</span>
1050
+ <span class="${ok ? 'badge-ok' : 'badge-warn'}">${ok ? 'Executable' : 'Simulated Check'}</span>
1051
+ `;
1052
+ diagList.appendChild(row);
1053
+ }
1054
+
1055
+ } catch (e) {
1056
+ console.error("Failed to load server status: ", e);
1057
+ }
1058
+ }
1059
+
1060
+ // Tab Switching
1061
+ function switchTab(tabId) {
1062
+ document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
1063
+ document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
1064
+
1065
+ const idx = ['trace', 'code', 'stdout'].indexOf(tabId);
1066
+ document.querySelectorAll('.tab-btn')[idx].classList.add('active');
1067
+ document.getElementById('tab-' + tabId).classList.add('active');
1068
+ }
1069
+
1070
+ // Log entry helper
1071
+ function appendLog(tag, msg, detail = null) {
1072
+ const container = document.getElementById('log-container');
1073
+ const entry = document.createElement('div');
1074
+ entry.className = 'log-entry';
1075
+
1076
+ const timeStr = new Date().toTimeString().split(' ')[0];
1077
+
1078
+ let tagClass = 'tag-status';
1079
+ if (tag === 'Thought') tagClass = 'tag-thought';
1080
+ if (tag === 'Code') tagClass = 'tag-code';
1081
+ if (tag === 'Execution') tagClass = 'tag-execution';
1082
+ if (tag === 'Error') tagClass = 'tag-error';
1083
+
1084
+ entry.innerHTML = `
1085
+ <span class="log-time">${timeStr}</span>
1086
+ <span class="log-tag ${tagClass}">${tag}</span>
1087
+ <span>${msg}</span>
1088
+ `;
1089
+
1090
+ if (detail) {
1091
+ const pre = document.createElement('pre');
1092
+ pre.innerText = detail;
1093
+ entry.appendChild(pre);
1094
+ }
1095
+
1096
+ container.appendChild(entry);
1097
+ container.scrollTop = container.scrollHeight;
1098
+ }
1099
+
1100
+ function copyGeneratedCode() {
1101
+ const codeText = document.getElementById('code-content').innerText;
1102
+ navigator.clipboard.writeText(codeText);
1103
+ const btn = document.querySelector('.copy-btn');
1104
+ btn.innerText = 'Copied!';
1105
+ setTimeout(() => btn.innerText = 'Copy', 2000);
1106
+ }
1107
+
1108
+ // Draw Concept Network Graph
1109
+ function drawGraph(nodesData, edgesData, highlightPath = []) {
1110
+ const container = document.getElementById('network-canvas');
1111
+
1112
+ // Build Network Nodes
1113
+ const nodes = new vis.DataSet(
1114
+ nodesData.map(n => {
1115
+ const isHighlighted = highlightPath.includes(n.name);
1116
+ return {
1117
+ id: n.name,
1118
+ label: n.name.replace('_', ' '),
1119
+ color: {
1120
+ background: isHighlighted ? '#6366f1' : '#161c30',
1121
+ border: isHighlighted ? '#a5b4fc' : '#334155',
1122
+ highlight: { background: '#6366f1', border: '#a5b4fc' }
1123
+ },
1124
+ font: { color: '#f8fafc', size: 12, face: 'Outfit' },
1125
+ shape: 'box',
1126
+ borderWidth: isHighlighted ? 2.5 : 1,
1127
+ margin: 10
1128
+ };
1129
+ })
1130
+ );
1131
+
1132
+ // Deduplicate Edges
1133
+ const edgeMap = {};
1134
+ edgesData.forEach(e => {
1135
+ const key = `${e.from}->${e.to}`;
1136
+ edgeMap[key] = e;
1137
+ });
1138
+
1139
+ // Build Network Edges
1140
+ const edges = new vis.DataSet(
1141
+ Object.values(edgeMap).map(e => {
1142
+ let isHighlighted = false;
1143
+ for (let i = 0; i < highlightPath.length - 1; i++) {
1144
+ if (highlightPath[i] === e.from && highlightPath[i+1] === e.to) {
1145
+ isHighlighted = true;
1146
+ break;
1147
+ }
1148
+ }
1149
+
1150
+ return {
1151
+ from: e.from,
1152
+ to: e.to,
1153
+ arrows: 'to',
1154
+ color: {
1155
+ color: isHighlighted ? '#10b981' : '#334155',
1156
+ highlight: isHighlighted ? '#10b981' : '#475569'
1157
+ },
1158
+ width: isHighlighted ? 3 : 1,
1159
+ smooth: { type: 'curvedCW', roundness: 0.15 }
1160
+ };
1161
+ })
1162
+ );
1163
+
1164
+ const data = { nodes, edges };
1165
+ const options = {
1166
+ physics: {
1167
+ stabilization: true,
1168
+ barnesHut: { gravitationalConstant: -2000, springLength: 150 }
1169
+ }
1170
+ };
1171
+
1172
+ network = new vis.Network(container, data, options);
1173
+ }
1174
+
1175
+ // Run Routing Bars animation
1176
+ function updateRoutingBars(probs) {
1177
+ const list = document.getElementById('routing-bars-list');
1178
+ list.innerHTML = '';
1179
+
1180
+ const sorted = Object.entries(probs).sort((a,b) => b[1] - a[1]);
1181
+ for (const [dom, p] of sorted) {
1182
+ const pct = Math.round(p * 100);
1183
+ const row = document.createElement('div');
1184
+ row.className = 'bar-row';
1185
+
1186
+ // Highlight active experts
1187
+ const isActive = p >= 0.4;
1188
+ const fillStyle = isActive ? 'background: linear-gradient(90deg, #6366f1, #8b5cf6)' : 'background: #475569';
1189
+
1190
+ row.innerHTML = `
1191
+ <div class="bar-label" style="color: ${isActive ? 'var(--text-primary)' : 'var(--text-secondary)'}">${dom}</div>
1192
+ <div class="bar-container">
1193
+ <div class="bar-fill" style="width: ${pct}%; ${fillStyle}"></div>
1194
+ </div>
1195
+ <div class="bar-val" style="color: ${isActive ? 'var(--accent-indigo-light)' : 'var(--text-secondary)'}">${pct}%</div>
1196
+ `;
1197
+ list.appendChild(row);
1198
+ }
1199
+ }
1200
+
1201
+ // Execute Agent
1202
+ document.getElementById('btn-execute').addEventListener('click', async () => {
1203
+ const question = document.getElementById('prompt-input').value.trim();
1204
+ const language = document.getElementById('lang-select').value;
1205
+ const maxIterations = document.getElementById('iter-slider').value;
1206
+ const temperature = document.getElementById('temp-slider').value;
1207
+
1208
+ if (!question) {
1209
+ alert("Please enter a coding task first!");
1210
+ return;
1211
+ }
1212
+
1213
+ const btn = document.getElementById('btn-execute');
1214
+ btn.disabled = true;
1215
+ btn.innerHTML = '<span class="spinner"></span> <span>Running Agent...</span>';
1216
+
1217
+ // Clear visual logs
1218
+ document.getElementById('log-container').innerHTML = '';
1219
+ document.getElementById('code-content').innerText = '// Initializing generation...';
1220
+ document.getElementById('stdout-output').innerText = 'Awaiting run output...';
1221
+ switchTab('trace');
1222
+
1223
+ appendLog('System', `Initiating autonomous execution loop for language: ${language.toUpperCase()}`);
1224
+
1225
+ if (activeEventSource) {
1226
+ activeEventSource.close();
1227
+ }
1228
+
1229
+ // Start SSE request
1230
+ const eventUrl = `/api/agent/run?` + new URLSearchParams({
1231
+ question: question,
1232
+ language: language,
1233
+ max_iterations: maxIterations,
1234
+ temperature: temperature
1235
+ }).toString();
1236
+
1237
+ activeEventSource = new EventSource(eventUrl);
1238
+
1239
+ activeEventSource.onmessage = (event) => {
1240
+ const res = JSON.parse(event.data);
1241
+ const type = res.event;
1242
+ const payload = res.data;
1243
+
1244
+ if (type === 'status') {
1245
+ appendLog('System', payload);
1246
+ } else if (type === 'thought') {
1247
+ appendLog('Thought', payload);
1248
+ } else if (type === 'routing') {
1249
+ // Update VIS Network and MoE Routing Bars
1250
+ updateRoutingBars(payload.domain_probabilities);
1251
+ drawGraph(payload.nodes, payload.edges, payload.reasoning_path);
1252
+ appendLog('System', `CAT V3 Router selected experts: [${payload.activated_domains.join(', ')}]. Path predicted: ${payload.reasoning_path.join(' -> ')}`);
1253
+ } else if (type === 'agent_log') {
1254
+ const logType = payload.type;
1255
+ if (logType === 'status') {
1256
+ appendLog('System', `[Iter ${payload.iteration}] ${payload.message}`);
1257
+ } else if (logType === 'thought') {
1258
+ appendLog('Thought', `[Iter ${payload.iteration}] ${payload.message}`);
1259
+ } else if (logType === 'code') {
1260
+ appendLog('Code', `[Iter ${payload.iteration}] Generated code solution.`, payload.explanation);
1261
+ document.getElementById('code-content').innerText = payload.code;
1262
+ } else if (logType === 'execution') {
1263
+ let execDetail = `Exit Code: ${payload.exit_code}\n`;
1264
+ if (payload.stdout.trim()) execDetail += `\nSTDOUT:\n${payload.stdout}\n`;
1265
+ if (payload.stderr.trim()) execDetail += `\nSTDERR:\n${payload.stderr}\n`;
1266
+
1267
+ appendLog('Execution', `[Iter ${payload.iteration}] Executed sandbox run (Simulated: ${payload.is_simulated})`, execDetail);
1268
+ } else if (logType === 'error') {
1269
+ appendLog('Error', `[Iter ${payload.iteration}] ${payload.message}`);
1270
+ }
1271
+ } else if (type === 'done') {
1272
+ appendLog('System', `Autonomous loop finished. Success: ${payload.success} in ${payload.iterations} iterations.`);
1273
+
1274
+ // Display final output in Stdout tab
1275
+ let stdoutText = `Status: ${payload.success ? 'Success' : 'Failure'}\n`;
1276
+ stdoutText += `Iterations run: ${payload.iterations}\n`;
1277
+ stdoutText += `Exit Code: ${payload.exit_code}\n\n`;
1278
+ stdoutText += `=== STDOUT ===\n${payload.stdout}\n\n`;
1279
+ stdoutText += `=== STDERR ===\n${payload.stderr}\n`;
1280
+
1281
+ document.getElementById('stdout-output').innerText = stdoutText;
1282
+ document.getElementById('code-content').innerText = payload.code;
1283
+
1284
+ // Switch tab to code if success, otherwise stdout
1285
+ if (payload.success) {
1286
+ switchTab('code');
1287
+ } else {
1288
+ switchTab('stdout');
1289
+ }
1290
+
1291
+ btn.disabled = false;
1292
+ btn.innerHTML = '<span>Run Coding Agent</span>';
1293
+ activeEventSource.close();
1294
+ } else if (type === 'error') {
1295
+ appendLog('Error', payload);
1296
+ btn.disabled = false;
1297
+ btn.innerHTML = '<span>Run Coding Agent</span>';
1298
+ activeEventSource.close();
1299
+ }
1300
+ };
1301
+
1302
+ activeEventSource.onerror = (e) => {
1303
+ appendLog('Error', "Connection to server EventStream closed unexpectedly.");
1304
+ btn.disabled = false;
1305
+ btn.innerHTML = '<span>Run Coding Agent</span>';
1306
+ if (activeEventSource) activeEventSource.close();
1307
+ };
1308
+ });
1309
+
1310
+ // Load baseline status on page show
1311
+ fetchStatus();
1312
+
1313
+ // Poll status every 10 seconds
1314
+ setInterval(fetchStatus, 10000);
1315
+ </script>
1316
+ </body>
1317
+ </html>
1318
+ """
1319
+
1320
+ def run(port=8002):
1321
+ server_address = ('', port)
1322
+ httpd = ThreadingHTTPServer(server_address, CodingLabRequestHandler)
1323
+ print(f"Starting Antigravity Autonomous Coding Lab server on port {port}...")
1324
+ try:
1325
+ httpd.serve_forever()
1326
+ except KeyboardInterrupt:
1327
+ print("\nShutting down server.")
1328
+ httpd.server_close()
1329
+
1330
+ if __name__ == "__main__":
1331
+ port = 8002
1332
+ if len(sys.argv) > 1:
1333
+ try:
1334
+ port = int(sys.argv[1])
1335
+ except ValueError:
1336
+ pass
1337
+ run(port)