-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
964 lines (768 loc) · 35.6 KB
/
api.py
File metadata and controls
964 lines (768 loc) · 35.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
"""
SiliconCrew Architect - FastAPI Backend
Production-grade API server for the RTL Design Agent.
Provides REST endpoints and WebSocket streaming for the Next.js frontend.
"""
import os
import json
import asyncio
from datetime import datetime
from typing import Optional, List, Dict, Any
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import yaml
import aiosqlite
from dotenv import load_dotenv
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, ToolMessage
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from src.agents.architect import create_architect_agent, load_system_prompt
from src.model_catalog import DEFAULT_MODEL, PRICING, normalize_model_name
from src.utils.session_manager import SessionManager
from src.utils.attempt_logger import log_tool_call, log_tool_result
from src.tools.design_report import save_design_report
from src.tools.synthesis_manager import get_run_dir, list_synthesis_runs
# Load environment
load_dotenv()
# =============================================================================
# CONFIGURATION
# =============================================================================
BASE_DIR = os.path.dirname(__file__)
WORKSPACE_DIR = os.environ.get("RTL_WORKSPACE") or os.path.join(BASE_DIR, "workspace")
_DATA_DIR = os.environ.get("RTL_DATA_DIR") or os.path.join(os.path.expanduser("~"), ".siliconcrew")
os.makedirs(_DATA_DIR, exist_ok=True)
DB_PATH = os.path.join(_DATA_DIR, "state.db")
# Initialize Session Manager
session_manager = SessionManager(base_dir=WORKSPACE_DIR, db_path=DB_PATH)
# =============================================================================
# PYDANTIC MODELS
# =============================================================================
class ProjectCreate(BaseModel):
name: str
class ProjectResponse(BaseModel):
id: str
name: str
created_at: Optional[str] = None
class SessionCreate(BaseModel):
name: str
model: str = DEFAULT_MODEL
project_id: Optional[str] = None
class SessionPatch(BaseModel):
project_id: Optional[str] = None # None = remove from project
class SessionResponse(BaseModel):
id: str
name: Optional[str] = None
model_name: Optional[str] = None
project_id: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
total_tokens: int = 0
total_cost: float = 0.0
class MessageResponse(BaseModel):
role: str
content: str
tool_calls: Optional[List[Dict[str, Any]]] = None
tool_results: Optional[List[Dict[str, Any]]] = None
class FileInfo(BaseModel):
name: str
path: str
type: str
size: int
modified: str
class SpecResponse(BaseModel):
filename: str
content: str
parsed: Optional[Dict[str, Any]] = None
class CodeFile(BaseModel):
filename: str
content: str
language: str = "verilog"
class SynthesisRunResponse(BaseModel):
run_id: str
status: str
updated_at: Optional[str] = None
created_at: Optional[str] = None
finished_at: Optional[str] = None
top_module: Optional[str] = None
platform: Optional[str] = None
elapsed_sec: Optional[float] = None
summary_metrics: Optional[Dict[str, Any]] = None
auto_checks: Optional[Dict[str, Any]] = None
report_available: bool = False
report_filename: Optional[str] = None
class ReportResponse(BaseModel):
filename: str
content: str
run_id: Optional[str] = None
# =============================================================================
# HELPER FUNCTIONS
# =============================================================================
def get_clean_content(msg) -> str:
"""Extract clean text content from a message."""
content = msg.content
if isinstance(content, list):
text_blocks = []
for block in content:
if isinstance(block, dict):
if block.get("type") == "text":
text_blocks.append(block.get("text", ""))
elif isinstance(block, str):
text_blocks.append(block)
return "\n".join(text_blocks)
return str(content) if content else ""
def calculate_cost(input_tokens: int, output_tokens: int, model_name: str) -> float:
"""Calculate cost based on token usage."""
canonical_model = normalize_model_name(model_name)
rates = PRICING.get(canonical_model, PRICING[DEFAULT_MODEL])
return (input_tokens / 1_000_000 * rates["input"]) + (output_tokens / 1_000_000 * rates["output"])
def format_tool_call_for_api(tool_call: dict) -> dict:
"""Format a tool call for API response."""
return {
"id": tool_call.get("id", ""),
"name": tool_call.get("name", "unknown"),
"args": tool_call.get("args", {})
}
def format_tool_result_for_api(content: str) -> dict:
"""Format a tool result for API response."""
status = "success"
# Prefer structured tool statuses when the tool returned JSON.
try:
parsed = json.loads(content)
if isinstance(parsed, dict):
parsed_status = parsed.get("status")
parsed_success = parsed.get("success")
if isinstance(parsed_status, str) and parsed_status.strip():
status = parsed_status.strip()
elif isinstance(parsed_success, bool):
status = "success" if parsed_success else "error"
except Exception:
if "Error" in content or "FAILED" in content or "Fail" in content:
status = "error"
elif "Success" in content or "PASSED" in content or "Pass" in content:
status = "success"
return {
"status": status,
"content": content[:5000] if len(content) > 5000 else content
}
def resolve_report_path(workspace: str, run_id: Optional[str] = None) -> tuple[Optional[str], Optional[str]]:
if run_id:
run_dir = get_run_dir(workspace, run_id)
if run_dir:
report_path = os.path.join(run_dir, "design_report.md")
if os.path.exists(report_path):
return report_path, run_id
return None, run_id
return None, None
latest_run_dir = get_run_dir(workspace, None)
if latest_run_dir:
report_path = os.path.join(latest_run_dir, "design_report.md")
if os.path.exists(report_path):
return report_path, os.path.basename(latest_run_dir)
report_files = sorted(
[f for f in os.listdir(workspace) if f.endswith("_report.md")],
key=lambda x: os.path.getmtime(os.path.join(workspace, x)),
reverse=True
)
if report_files:
return os.path.join(workspace, report_files[0]), None
return None, None
@asynccontextmanager
async def open_checkpointer(db_path: str):
"""
Open AsyncSqliteSaver with compatibility for aiosqlite variants that do not
expose Connection.is_alive().
"""
conn = await aiosqlite.connect(db_path)
# langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver expects this method.
if not hasattr(conn, "is_alive"):
def _is_alive() -> bool:
return bool(getattr(conn, "_running", False))
setattr(conn, "is_alive", _is_alive)
memory = AsyncSqliteSaver(conn)
try:
yield memory
finally:
await conn.close()
# =============================================================================
# LIFESPAN
# =============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup and shutdown events."""
# Startup
print(f"[API] Starting SiliconCrew API server")
print(f"[API] Workspace: {WORKSPACE_DIR}")
print(f"[API] Database: {DB_PATH}")
if not os.path.exists(WORKSPACE_DIR):
os.makedirs(WORKSPACE_DIR)
yield
# Shutdown
print("[API] Shutting down...")
# =============================================================================
# FASTAPI APP
# =============================================================================
app = FastAPI(
title="SiliconCrew Architect API",
description="API for the RTL Design Agent",
version="1.0.0",
lifespan=lifespan
)
# CORS for Next.js frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# =============================================================================
# SESSION ENDPOINTS
# =============================================================================
@app.get("/api/sessions", response_model=List[SessionResponse])
async def list_sessions():
"""List all sessions."""
sessions = session_manager.get_all_sessions()
result = []
for session_id in sessions:
meta = session_manager.get_session_metadata(session_id)
result.append(SessionResponse(
id=session_id,
name=meta.get("session_name") if meta else None,
model_name=meta.get("model_name") if meta else None,
project_id=meta.get("project_id") if meta else None,
created_at=str(meta.get("created_at")) if meta else None,
updated_at=str(meta.get("updated_at")) if meta and meta.get("updated_at") else None,
total_tokens=meta.get("total_tokens", 0) if meta else 0,
total_cost=meta.get("total_cost", 0.0) if meta else 0.0
))
return result
@app.post("/api/sessions", response_model=SessionResponse)
async def create_session(data: SessionCreate):
"""Create a new session."""
try:
model_name = normalize_model_name(data.model)
session_id = session_manager.create_session(
tag=data.name, model_name=model_name, project_id=data.project_id
)
meta = session_manager.get_session_metadata(session_id)
return SessionResponse(
id=session_id,
name=meta.get("session_name") if meta else data.name,
model_name=model_name,
project_id=data.project_id,
created_at=str(meta.get("created_at")) if meta else None,
updated_at=str(meta.get("updated_at")) if meta and meta.get("updated_at") else None,
total_tokens=0,
total_cost=0.0
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except FileExistsError as e:
raise HTTPException(status_code=409, detail=str(e))
@app.get("/api/sessions/{session_id:path}", response_model=SessionResponse)
async def get_session(session_id: str):
"""Get session details."""
meta = session_manager.get_session_metadata(session_id)
if not meta:
raise HTTPException(status_code=404, detail="Session not found")
return SessionResponse(
id=session_id,
name=meta.get("session_name"),
model_name=meta.get("model_name"),
project_id=meta.get("project_id"),
created_at=str(meta.get("created_at")),
updated_at=str(meta.get("updated_at")) if meta.get("updated_at") else None,
total_tokens=meta.get("total_tokens", 0),
total_cost=meta.get("total_cost", 0.0)
)
@app.delete("/api/sessions/{session_id:path}")
async def delete_session(session_id: str):
"""Delete a session."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
session_manager.delete_session(session_id)
return {"status": "deleted", "session_id": session_id}
@app.patch("/api/sessions/{session_id:path}", response_model=SessionResponse)
async def patch_session(session_id: str, data: SessionPatch):
"""Move a session to a different project (or remove from project)."""
meta = session_manager.get_session_metadata(session_id)
if not meta:
raise HTTPException(status_code=404, detail="Session not found")
try:
session_manager.move_session_to_project(session_id, data.project_id)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
meta = session_manager.get_session_metadata(session_id)
return SessionResponse(
id=session_id,
name=meta.get("session_name"),
model_name=meta.get("model_name"),
project_id=meta.get("project_id"),
created_at=str(meta.get("created_at")),
updated_at=str(meta.get("updated_at")) if meta.get("updated_at") else None,
total_tokens=meta.get("total_tokens", 0),
total_cost=meta.get("total_cost", 0.0),
)
# =============================================================================
# PROJECT ENDPOINTS
# =============================================================================
@app.get("/api/projects", response_model=List[ProjectResponse])
async def list_projects():
"""List all projects."""
projects = session_manager.get_all_projects()
return [ProjectResponse(id=p["id"], name=p["name"], created_at=str(p.get("created_at") or "")) for p in projects]
@app.post("/api/projects", response_model=ProjectResponse, status_code=201)
async def create_project(data: ProjectCreate):
"""Create a new project."""
try:
project = session_manager.create_project(data.name)
return ProjectResponse(id=project["id"], name=project["name"], created_at=str(project["created_at"]))
except ValueError as e:
raise HTTPException(status_code=409, detail=str(e))
@app.delete("/api/projects/{project_id}")
async def delete_project(project_id: str):
"""Delete a project (sessions are kept, unassigned)."""
if not session_manager.get_project(project_id):
raise HTTPException(status_code=404, detail="Project not found")
session_manager.delete_project(project_id)
return {"status": "deleted", "project_id": project_id}
# =============================================================================
# CHAT ENDPOINTS
# =============================================================================
@app.get("/api/chat/{session_id:path}/history")
async def get_chat_history(session_id: str) -> List[Dict[str, Any]]:
"""Get chat history for a session."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
try:
async with open_checkpointer(DB_PATH) as memory:
meta = session_manager.get_session_metadata(session_id)
model_name = normalize_model_name(meta.get("model_name", DEFAULT_MODEL) if meta else DEFAULT_MODEL)
agent_graph = create_architect_agent(checkpointer=memory, model_name=model_name)
config = {"configurable": {"thread_id": session_id}}
current_state = await agent_graph.aget_state(config)
if not current_state.values or "messages" not in current_state.values:
return []
messages = current_state.values["messages"]
history = []
for msg in messages:
if isinstance(msg, SystemMessage):
continue
elif isinstance(msg, HumanMessage):
history.append({
"role": "user",
"content": get_clean_content(msg)
})
elif isinstance(msg, AIMessage):
entry = {
"role": "assistant",
"content": get_clean_content(msg),
"tool_calls": []
}
if hasattr(msg, "tool_calls") and msg.tool_calls:
entry["tool_calls"] = [
format_tool_call_for_api(tc) for tc in msg.tool_calls
]
history.append(entry)
elif hasattr(msg, "tool_call_id"):
# Tool result - attach to previous assistant message
result = format_tool_result_for_api(msg.content)
if history and history[-1]["role"] == "assistant":
if "tool_results" not in history[-1]:
history[-1]["tool_results"] = []
history[-1]["tool_results"].append({
"tool_call_id": msg.tool_call_id,
**result
})
return history
except Exception as e:
print(f"[ERROR] Loading history: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.websocket("/api/chat/{session_id:path}")
async def chat_websocket(websocket: WebSocket, session_id: str):
"""WebSocket endpoint for streaming chat."""
await websocket.accept()
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
await websocket.send_json({"type": "error", "error": "Session not found"})
await websocket.close()
return
try:
while True:
# Receive message from client
data = await websocket.receive_json()
message = data.get("message", "")
if not message.strip():
await websocket.send_json({"type": "error", "error": "Empty message"})
continue
# Set workspace path for tools
os.environ["RTL_WORKSPACE"] = workspace
print(f"[CHAT] Session: {session_id} | Message: {message[:50]}...")
# Initialize agent with AsyncSqliteSaver (supports async streaming/state)
async with open_checkpointer(DB_PATH) as memory:
meta = session_manager.get_session_metadata(session_id)
model_name = normalize_model_name(meta.get("model_name", DEFAULT_MODEL) if meta else DEFAULT_MODEL)
agent_graph = create_architect_agent(checkpointer=memory, model_name=model_name)
config = {"configurable": {"thread_id": session_id}, "recursion_limit": 50}
# Check for corrupted state
snapshot = await agent_graph.aget_state(config)
input_messages = []
if snapshot.values and snapshot.values.get("messages"):
messages = snapshot.values["messages"]
pending_tool_ids = set()
for msg in messages:
if isinstance(msg, AIMessage) and hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
pending_tool_ids.add(tc.get("id"))
elif hasattr(msg, "tool_call_id"):
pending_tool_ids.discard(msg.tool_call_id)
# Fix corrupted state with fake responses
if pending_tool_ids:
for tool_id in pending_tool_ids:
fake_response = ToolMessage(
content="[Tool execution was interrupted. Please retry the operation.]",
tool_call_id=tool_id
)
input_messages.append(fake_response)
if not snapshot.values or not snapshot.values.get("messages"):
input_messages.append(SystemMessage(content=load_system_prompt()))
input_messages.append(("user", message))
# Stream using LangGraph's astream()
await websocket.send_json({"type": "start"})
total_input_tokens = 0
total_output_tokens = 0
pending_tool_calls: Dict[str, Dict[str, Any]] = {}
try:
async for event in agent_graph.astream(
{"messages": input_messages},
config,
stream_mode="updates"
):
if "agent" in event:
msg = event["agent"]["messages"][-1]
# Send text content
text = get_clean_content(msg)
if text:
await websocket.send_json({
"type": "text",
"content": text
})
# Track tokens
if hasattr(msg, "usage_metadata") and msg.usage_metadata:
total_input_tokens += msg.usage_metadata.get("input_tokens", 0)
total_output_tokens += msg.usage_metadata.get("output_tokens", 0)
# Send tool calls
if hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
tc_id = tc.get("id", "")
tc_name = tc.get("name", "unknown")
tc_args = tc.get("args", {}) if isinstance(tc.get("args"), dict) else {}
if tc_id:
pending_tool_calls[tc_id] = {"name": tc_name, "args": tc_args}
log_tool_call(
workspace=workspace,
session_id=session_id,
source="api_ws",
tool=tc_name,
arguments=tc_args,
tool_call_id=tc_id or None,
)
await websocket.send_json({
"type": "tool_call",
"tool": format_tool_call_for_api(tc)
})
elif "tools" in event:
msg = event["tools"]["messages"][-1]
result = format_tool_result_for_api(msg.content)
call_meta = pending_tool_calls.pop(msg.tool_call_id, {})
log_tool_result(
workspace=workspace,
session_id=session_id,
source="api_ws",
tool=call_meta.get("name", "unknown"),
result=msg.content,
status="success" if result.get("status") == "success" else "error",
tool_call_id=msg.tool_call_id,
arguments=call_meta.get("args", {}),
)
await websocket.send_json({
"type": "tool_result",
"tool_call_id": msg.tool_call_id,
**result
})
# Update token usage
if total_input_tokens > 0 or total_output_tokens > 0:
current_meta = session_manager.get_session_metadata(session_id)
if current_meta:
new_input = current_meta.get("input_tokens", 0) + total_input_tokens
new_output = current_meta.get("output_tokens", 0) + total_output_tokens
cached = current_meta.get("cached_tokens", 0)
new_cost = calculate_cost(new_input, new_output, model_name)
session_manager.update_session_stats(session_id, new_input, new_output, cached, new_cost)
await websocket.send_json({
"type": "done",
"tokens": {
"input": total_input_tokens,
"output": total_output_tokens
}
})
except Exception as e:
print(f"[ERROR] Agent error: {e}")
await websocket.send_json({
"type": "error",
"error": str(e)
})
except WebSocketDisconnect:
print(f"[CHAT] WebSocket disconnected: {session_id}")
except Exception as e:
print(f"[ERROR] WebSocket error: {e}")
try:
await websocket.send_json({"type": "error", "error": str(e)})
except:
pass
# =============================================================================
# WORKSPACE/ARTIFACTS ENDPOINTS
# =============================================================================
@app.get("/api/workspace/{session_id:path}/files")
async def list_workspace_files(session_id: str) -> List[FileInfo]:
"""List all files in the workspace."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
files = []
for item in os.listdir(workspace):
item_path = os.path.join(workspace, item)
if os.path.isfile(item_path):
stat = os.stat(item_path)
# Determine file type
ext = os.path.splitext(item)[1].lower()
file_type = "unknown"
if ext in [".v", ".sv"]:
file_type = "verilog"
elif ext == ".yaml":
file_type = "spec" if "_spec" in item else "yaml"
elif ext == ".vcd":
file_type = "waveform"
elif ext == ".gds":
file_type = "layout"
elif ext == ".svg":
file_type = "schematic"
elif ext == ".md":
file_type = "report"
files.append(FileInfo(
name=item,
path=item_path,
type=file_type,
size=stat.st_size,
modified=datetime.fromtimestamp(stat.st_mtime).isoformat()
))
return sorted(files, key=lambda f: f.modified, reverse=True)
@app.get("/api/workspace/{session_id:path}/spec")
async def get_spec(session_id: str) -> SpecResponse:
"""Get the latest spec file."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
spec_files = sorted(
[f for f in os.listdir(workspace) if f.endswith("_spec.yaml")],
key=lambda x: os.path.getmtime(os.path.join(workspace, x)),
reverse=True
)
if not spec_files:
raise HTTPException(status_code=404, detail="No spec files found")
spec_file = spec_files[0]
spec_path = os.path.join(workspace, spec_file)
with open(spec_path, "r") as f:
content = f.read()
try:
parsed = yaml.safe_load(content)
except:
parsed = None
return SpecResponse(
filename=spec_file,
content=content,
parsed=parsed
)
@app.get("/api/workspace/{session_id:path}/code")
async def get_code_files(session_id: str) -> List[CodeFile]:
"""Get all Verilog/SystemVerilog files."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
files = sorted([
f for f in os.listdir(workspace)
if f.endswith(('.v', '.sv')) and os.path.isfile(os.path.join(workspace, f))
])
result = []
for filename in files:
with open(os.path.join(workspace, filename), "r", errors='ignore') as f:
content = f.read()
lang = "systemverilog" if filename.endswith(".sv") else "verilog"
result.append(CodeFile(filename=filename, content=content, language=lang))
return result
@app.get("/api/workspace/{session_id:path}/code/{filename:path}")
async def get_code_file(session_id: str, filename: str) -> CodeFile:
"""Get a specific code file."""
workspace = session_manager.get_workspace_path(session_id)
file_path = os.path.join(workspace, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
real_workspace = os.path.realpath(workspace)
real_file = os.path.realpath(file_path)
if not real_file.startswith(real_workspace):
raise HTTPException(status_code=403, detail="Access denied")
with open(file_path, "r", errors='ignore') as f:
content = f.read()
lang = "systemverilog" if filename.endswith(".sv") else "verilog"
return CodeFile(filename=filename, content=content, language=lang)
@app.get("/api/workspace/{session_id:path}/waveforms")
async def list_waveform_files(session_id: str) -> List[str]:
"""List VCD files in the workspace."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
return [f for f in os.listdir(workspace) if f.endswith(".vcd")]
@app.get("/api/workspace/{session_id:path}/waveform/{filename:path}")
async def get_waveform_data(session_id: str, filename: str):
"""Get parsed VCD waveform data."""
workspace = session_manager.get_workspace_path(session_id)
vcd_path = os.path.join(workspace, filename)
if not os.path.exists(vcd_path):
raise HTTPException(status_code=404, detail="File not found")
real_workspace = os.path.realpath(workspace)
real_vcd = os.path.realpath(vcd_path)
if not real_vcd.startswith(real_workspace):
raise HTTPException(status_code=403, detail="Access denied")
try:
from vcdvcd import VCDVCD
vcd = VCDVCD(vcd_path)
signals = vcd.get_signals()
endtime = vcd.endtime
# Parse signals
signal_data = []
for sig_name in signals[:20]: # Limit to 20 signals
try:
sig = vcd[sig_name]
tv = sig.tv
times = []
values = []
for t, v in tv:
times.append(t)
try:
if isinstance(v, str):
v_clean = v.lower().replace('x', '0').replace('z', '0')
val = int(v_clean, 2) if v_clean else 0
else:
val = int(v)
except ValueError:
val = 0
values.append(val)
signal_data.append({
"name": sig_name.split('.')[-1],
"full_name": sig_name,
"times": times,
"values": values
})
except:
continue
return {
"filename": filename,
"endtime": endtime,
"signals": signal_data
}
except ImportError:
raise HTTPException(status_code=500, detail="vcdvcd library not installed")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/workspace/{session_id:path}/synthesis-runs", response_model=List[SynthesisRunResponse])
async def get_synthesis_runs(session_id: str):
"""List synthesis runs for a workspace."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
return [SynthesisRunResponse(**item) for item in list_synthesis_runs(workspace)]
@app.get("/api/workspace/{session_id:path}/report", response_model=ReportResponse)
async def get_report(session_id: str, run_id: Optional[str] = Query(default=None)) -> ReportResponse:
"""Get the latest available report or a report for a specific synthesis run."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
report_path, resolved_run_id = resolve_report_path(workspace, run_id=run_id)
if not report_path:
raise HTTPException(status_code=404, detail="No report found")
with open(report_path, "r", encoding="utf-8") as f:
content = f.read()
return ReportResponse(filename=os.path.basename(report_path), content=content, run_id=resolved_run_id)
@app.post("/api/workspace/{session_id:path}/report/generate", response_model=ReportResponse)
async def generate_report(session_id: str, run_id: Optional[str] = Query(default=None)) -> ReportResponse:
"""Generate a design report for the selected synthesis run or latest available run."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
try:
report_path = save_design_report(workspace, run_id=run_id)
with open(report_path, "r", encoding="utf-8") as f:
content = f.read()
resolved_run_id = None
report_dir = os.path.dirname(report_path)
if os.path.basename(report_path) == "design_report.md" and os.path.realpath(report_dir) != os.path.realpath(workspace):
resolved_run_id = os.path.basename(report_dir)
return ReportResponse(filename=os.path.basename(report_path), content=content, run_id=resolved_run_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/workspace/{session_id:path}/layouts")
async def list_layout_files(session_id: str) -> List[str]:
"""List GDS files in the workspace."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
gds_files = []
for root, dirs, files in os.walk(workspace):
for f in files:
if f.endswith(".gds"):
rel_path = os.path.relpath(os.path.join(root, f), workspace)
gds_files.append(rel_path)
return gds_files
@app.get("/api/workspace/{session_id:path}/schematics")
async def list_schematic_files(session_id: str) -> List[str]:
"""List SVG schematic files in the workspace."""
workspace = session_manager.get_workspace_path(session_id)
if not os.path.exists(workspace):
raise HTTPException(status_code=404, detail="Session not found")
return [f for f in os.listdir(workspace) if f.endswith(".svg") and not f.endswith(".gds.svg")]
@app.get("/api/workspace/{session_id:path}/file/{filename:path}")
async def get_file_content(session_id: str, filename: str):
"""Get raw file content."""
workspace = session_manager.get_workspace_path(session_id)
file_path = os.path.join(workspace, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
# Security check - ensure file is within workspace
real_workspace = os.path.realpath(workspace)
real_file = os.path.realpath(file_path)
if not real_file.startswith(real_workspace):
raise HTTPException(status_code=403, detail="Access denied")
with open(file_path, "r", errors='ignore') as f:
content = f.read()
return {"filename": filename, "content": content}
# =============================================================================
# HEALTH CHECK
# =============================================================================
@app.get("/api/health")
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"version": "1.0.0",
"workspace": WORKSPACE_DIR,
"sessions": len(session_manager.get_all_sessions())
}
# =============================================================================
# MAIN
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)