-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathweb_app.py
More file actions
553 lines (447 loc) ยท 20.7 KB
/
web_app.py
File metadata and controls
553 lines (447 loc) ยท 20.7 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
#!/usr/bin/env python3
"""
Code Hack AI Expert - Multi-Project Web Interface
Connects to 7 MCP servers via streamable-http, creates a DeepAgent with
subagents for specialized tasks, and serves a WebSocket chat UI.
Usage:
# 1. Start all MCP servers:
bash start_servers.sh
# 2. Start the web interface:
uv run python web_app.py
# 3. Open http://localhost:8000
"""
import asyncio
import json
import os
import sys
import warnings
from pathlib import Path
from contextlib import asynccontextmanager, AsyncExitStack
# Bypass proxy for localhost MCP server connections
os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
warnings.filterwarnings("ignore", message="Core Pydantic V1 functionality")
import yaml
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse
from langchain_core.messages import AIMessage, ToolMessage
from langchain_openai import ChatOpenAI
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from langchain_mcp_adapters.tools import load_mcp_tools
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend
EXPERT_DIR = Path(__file__).parent
# โโโ Global State โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
agent = None
_exit_stack = None
# โโโ MCP Server URLs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
MCP_SERVERS = {
"filesystem-command": "http://localhost:8001/mcp",
"git-tools": "http://localhost:8002/mcp",
"code-intel": "http://localhost:8003/mcp",
"memory-store": "http://localhost:8004/mcp",
"code-review": "http://localhost:8005/mcp",
"multi-project": "http://localhost:8007/mcp",
"mermaid-chart": "http://localhost:8008/mcp",
}
def get_llm_model() -> ChatOpenAI:
"""Get the LLM model configured via environment variables."""
api_key = os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY")
base_url = os.environ.get("LLM_BASE_URL", "https://openrouter.ai/api/v1")
model_name = os.environ.get("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250514")
if not api_key:
raise ValueError(
"Please set OPENROUTER_API_KEY or OPENAI_API_KEY environment variable"
)
return ChatOpenAI(
model=model_name,
base_url=base_url,
api_key=api_key,
max_tokens=16000,
)
def get_subagent_model() -> ChatOpenAI:
"""Get the LLM model for subagents (cheaper/faster model)."""
api_key = os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY")
base_url = os.environ.get("LLM_BASE_URL", "https://openrouter.ai/api/v1")
model_name = os.environ.get("LLM_SUBAGENT_MODEL", "anthropic/claude-haiku-4-5-20251001")
return ChatOpenAI(
model=model_name,
base_url=base_url,
api_key=api_key,
max_tokens=8000,
)
def load_subagents(config_path: Path, mcp_tools: list) -> list:
"""Load subagent definitions from YAML and wire up their tools."""
if not config_path.exists():
print(f" (no subagents.yaml found, skipping subagents)")
return []
tool_lookup = {t.name: t for t in mcp_tools}
with open(config_path) as f:
config = yaml.safe_load(f)
subagent_model = get_subagent_model()
subagents = []
for name, spec in config.items():
subagent = {
"name": name,
"description": spec["description"],
"system_prompt": spec["system_prompt"],
"model": subagent_model,
}
if "tools" in spec:
subagent["tools"] = [
tool_lookup[t] for t in spec["tools"]
if t in tool_lookup
]
subagents.append(subagent)
return subagents
SYSTEM_PROMPT = """\
You are the **Code Hack AI Expert** โ a full-featured multi-project programming agent.
## Your Toolset (8 MCP Servers, 71+ tools)
### 1. Filesystem (filesystem-command)
- `read_file` / `read_file_lines` / `write_file` / `append_file` / `edit_file`
- `find_files` / `search_files_ag` / `list_directory` / `get_file_info`
- `execute_command` / `create_directory` / `get_current_directory`
### 2. Git Operations (git-tools)
- `git_status` / `git_diff` / `git_log` / `git_show`
- `git_add` / `git_commit` / `git_branch` / `git_create_branch` / `git_checkout`
- `git_stash` / `git_blame`
### 3. Code Intelligence (code-intel)
- `analyze_python_file` โ Deep Python file analysis (AST-level)
- `extract_symbols` โ Symbol extraction for Python/JS/TS/Java/Go/Rust
- `project_overview` โ Project panorama: directory tree, language distribution
- `find_references` โ Cross-file symbol reference search
- `dependency_graph` โ File import/imported-by relationships
### 4. Persistent Memory (memory-store)
- `memory_save` / `memory_get` / `memory_search` / `memory_list` / `memory_delete`
- `scratchpad_write` / `scratchpad_read` / `scratchpad_append`
- `qa_experience_save` / `qa_experience_search` / `qa_experience_get`
### 5. Code Review (code-review)
- `review_project` / `review_file` / `review_function` / `health_score`
- `find_long_functions` / `find_complex_functions` / `suggest_reorg`
- `review_diff_text`
- `ydiff_files` / `ydiff_commit` / `ydiff_git_changes` โ Structural AST-level diff (visual HTML reports)
### 8. Mermaid Chart (mermaid-chart)
- `render_mermaid` โ Render Mermaid code to interactive HTML and open in browser
- `flowchart` โ Generate flowcharts from structured node data
- `sequence_diagram` โ Generate sequence diagrams from interaction data
- `list_charts` / `open_chart` โ List and open generated chart files
### 7. Multi-Project Workspace (multi-project)
- `workspace_add` / `workspace_remove` / `workspace_list` / `workspace_overview`
- `workspace_search` / `workspace_find_files` / `workspace_find_dependencies`
- `workspace_read_file` / `workspace_edit_file` / `workspace_write_file`
- `workspace_git_status` / `workspace_git_diff` / `workspace_git_log` / `workspace_commit`
- `workspace_exec`
## Core Working Principles
### Understand First, Act Second
1. Use `project_overview` to understand project structure
2. Use `find_files` and `search_files_ag` to locate relevant files
3. Use `read_file_lines` to read key code sections
4. Use `analyze_python_file` or `extract_symbols` to understand code structure
5. Only start making changes after confirming understanding
### Precise Editing
- Prefer `edit_file` for precise replacements instead of rewriting entire files
- Read the file before modifying to ensure old_string is accurate
### Git Workflow
- Before modifying code, use `git_status` and `git_diff` to understand current state
- After completing related changes, proactively suggest committing
### Two-Phase Commit (Reviewer-Friendly AI Changes)
When changes involve both structural reorganization and logic modifications, **split into two commits**:
1. **Mechanical commit** โ add `#not-need-review` to commit message
- Moving functions/classes between files, renaming, reformatting, reordering
- Any **identity transformation** โ behavior unchanged before and after
2. **Logic commit** โ normal commit (no tag), reviewer must read this
- Adding/modifying business logic, changing behavior, bug fixes, new features
This lets reviewers run `git log --grep="#not-need-review" --invert-grep` to skip mechanical changes.
### Memory & Context
- Use `memory_save` to persist important project info and decisions
- At session start, use `memory_list` to check previous context
- Use `scratchpad` for complex task tracking
### Multi-Project Workflow
- Use `workspace_list` to see registered projects
- Use `workspace_add` to register new projects
- Use `workspace_search` for cross-project impact analysis
- Use `workspace_commit` for synchronized commits
### QA Experience Recording
- After successfully solving a problem, proactively ask the user to record it
- Use `qa_experience_save` to capture the experiment record
- Before tackling new problems, check `qa_experience_search` for prior patterns
### Safety First
- Never execute dangerous commands
- Confirm intent before modifying files
- Check current state before Git operations
- Never modify files you haven't read
## Style
- Concise and direct, no fluff
- Search code before making suggestions
- Think like an experienced senior engineer
- Proactively identify potential issues without over-engineering
"""
async def init_agent():
"""Initialize the DeepAgent by connecting to all MCP servers."""
global agent, _exit_stack
_exit_stack = AsyncExitStack()
await _exit_stack.__aenter__()
model = get_llm_model()
all_tools = []
print(" Connecting to MCP servers...")
for server_name, url in MCP_SERVERS.items():
try:
transport = await _exit_stack.enter_async_context(
streamablehttp_client(url)
)
read_stream, write_stream, _ = transport
session = await _exit_stack.enter_async_context(
ClientSession(read_stream, write_stream)
)
await session.initialize()
tools = await load_mcp_tools(session, server_name=server_name)
all_tools.extend(tools)
tool_names = [t.name for t in tools]
print(f" OK {server_name}: {len(tools)} tools โ {', '.join(tool_names[:5])}{'...' if len(tool_names) > 5 else ''}")
except Exception as e:
print(f" FAIL {server_name}: {e}")
print(f"\n Total: {len(all_tools)} tools loaded from {len(MCP_SERVERS)} servers")
# Load subagent definitions
subagents = load_subagents(EXPERT_DIR / "subagents.yaml", all_tools)
if subagents:
print(f" Subagents: {', '.join(s['name'] for s in subagents)}")
# Create DeepAgent with all tools, subagents, memory, and filesystem backend
agent = create_deep_agent(
model=model,
tools=all_tools,
subagents=subagents,
memory=["./AGENTS.md"],
backend=FilesystemBackend(root_dir=EXPERT_DIR),
system_prompt=SYSTEM_PROMPT,
)
return agent
async def cleanup():
"""Close all MCP connections."""
global _exit_stack
if _exit_stack:
await _exit_stack.aclose()
# โโโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def get_content_as_string(content) -> str:
"""Convert message content to string."""
if isinstance(content, str):
return content
elif isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
parts.append(item.get("text", ""))
return "\n".join(parts)
return str(content)
def get_tool_display(name: str, args: dict) -> tuple:
"""Get icon and status text for a tool call."""
# Subagent task delegation
if name == "task":
desc = args.get("description", "processing...")[:50]
return "๐", f"ๅงๆดพไปปๅก: {desc}..."
# Filesystem
if name in ("read_file", "read_file_lines"):
return "๐", f"่ฏปๅ: {args.get('file_path', 'file')}"
if name == "write_file":
return "โ๏ธ", f"ๅๅ
ฅ: {args.get('file_path', 'file')}"
if name == "edit_file":
return "โ๏ธ", f"็ผ่พ: {args.get('file_path', 'file')}"
if name == "append_file":
return "โ๏ธ", f"่ฟฝๅ : {args.get('file_path', 'file')}"
if name == "list_directory":
return "๐", f"ๅๅบ: {args.get('directory_path', '.')}"
if name == "execute_command":
return "โก", f"ๆง่ก: {args.get('command', '')[:50]}"
if name == "search_files_ag":
return "๐", f"ๆ็ดข: {args.get('pattern', '')[:40]}"
if name == "find_files":
return "๐", f"ๆฅๆพ: {args.get('pattern', '*')}"
# Git
if name.startswith("git_"):
return "๐", f"Git {name}"
# Code Intel
if name == "analyze_python_file":
return "๐งฌ", f"ๅๆ: {args.get('file_path', '')}"
if name == "project_overview":
return "๐บ๏ธ", f"้กน็ฎๆฆ่ง: {args.get('directory', '.')}"
if name == "find_references":
return "๐", f"ๅผ็จ: {args.get('symbol', '')}"
if name == "dependency_graph":
return "๐ธ๏ธ", f"ไพ่ต: {args.get('file_path', '')}"
if name == "extract_symbols":
return "๐งฌ", f"็ฌฆๅท: {args.get('file_path', '')}"
# Memory
if name == "memory_save":
return "๐พ", f"่ฎฐๅฟ: {args.get('key', '')}"
if name in ("memory_get", "memory_search"):
return "๐ง ", f"ๅๅฟ: {args.get('key', args.get('query', ''))}"
if name == "memory_list":
return "๐ง ", "ๅๅบ่ฎฐๅฟ"
if name in ("scratchpad_write", "scratchpad_append"):
return "๐", "ๅ่็จฟ"
if name == "scratchpad_read":
return "๐", "่ฏป่็จฟ"
if name == "qa_experience_save":
return "๐", f"่ฎฐๅฝ็ป้ช: {args.get('title', '')}"
if name == "qa_experience_search":
return "๐", f"ๆ็ดข็ป้ช: {args.get('query', '')}"
# Code Review
if name == "review_project":
return "๐ฌ", f"ๅฎกๆฅ้กน็ฎ: {args.get('project_dir', '')}"
if name == "review_file":
return "๐ฌ", f"ๅฎกๆฅๆไปถ: {args.get('file_path', '')}"
if name == "review_function":
return "๐ฌ", f"ๅฎกๆฅๅฝๆฐ: {args.get('function_name', '')}"
if name == "health_score":
return "๐ฏ", "ๅฅๅบท่ฏๅ"
if name == "find_long_functions":
return "๐", "่ถ
้ฟๅฝๆฐ"
if name == "find_complex_functions":
return "๐", "้ซๅคๆๅบฆๅฝๆฐ"
if name == "suggest_reorg":
return "๐ฆ", "้็ปๅปบ่ฎฎ"
if name == "review_diff_text":
return "๐ฌ", "ไปฃ็ ๅฏนๆฏๅฎกๆฅ"
# Code Refactor
if name == "auto_refactor":
return "๐ง", f"่ชๅจ้ๆ: {args.get('project_dir', '')}"
if name == "ydiff_files":
return "๐", "็ปๆๅ Diff"
if name == "ydiff_commit":
return "๐", f"Commit Diff: {args.get('commit_id', '')}"
if name == "ydiff_git_changes":
return "๐", "Git ๅๆด Diff"
# Mermaid Chart
if name == "render_mermaid":
return "๐", f"ๆธฒๆๅพ่กจ: {args.get('title', 'Mermaid Chart')}"
if name == "flowchart":
return "๐", f"ๆต็จๅพ: {args.get('title', 'Flowchart')}"
if name == "sequence_diagram":
return "๐", f"ๆถๅบๅพ: {args.get('title', 'Sequence Diagram')}"
if name == "list_charts":
return "๐", "ๅๅบๅพ่กจ"
if name == "open_chart":
return "๐", f"ๆๅผๅพ่กจ: {args.get('file_path', '')}"
# Multi-Project
if name == "workspace_add":
return "โ", f"ๆณจๅ้กน็ฎ: {args.get('alias', args.get('project_path', ''))}"
if name == "workspace_list":
return "๐", "ๅทฅไฝๅบๅ่กจ"
if name == "workspace_search":
return "๐", f"่ทจ้กน็ฎๆ็ดข: {args.get('pattern', '')[:40]}"
if name == "workspace_find_files":
return "๐", f"่ทจ้กน็ฎๆฅๆพ: {args.get('pattern', '')}"
if name == "workspace_find_dependencies":
return "๐ธ๏ธ", f"่ทจ้กน็ฎไพ่ต: {args.get('symbol', '')}"
if name == "workspace_read_file":
return "๐", f"[{args.get('project', '')}] {args.get('file_path', '')}"
if name == "workspace_edit_file":
return "โ๏ธ", f"[{args.get('project', '')}] {args.get('file_path', '')}"
if name == "workspace_git_status":
return "๐", "่ทจ้กน็ฎ Git ็ถๆ"
if name == "workspace_commit":
return "๐", f"ๅๅๆไบค: {args.get('message', '')[:40]}"
if name == "workspace_overview":
return "๐บ๏ธ", "ๅทฅไฝๅบๆฆ่ง"
if name == "workspace_exec":
return "โก", f"[{args.get('project', '')}] {args.get('command', '')[:40]}"
return "๐ง", name
# โโโ FastAPI App โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@asynccontextmanager
async def lifespan(app: FastAPI):
print()
print("=== Code Hack AI Expert (DeepAgent) ===")
print()
await init_agent()
print()
print(" Web UI: http://localhost:8000")
print()
yield
await cleanup()
print("Shutting down...")
app = FastAPI(title="Code Hack AI Expert", lifespan=lifespan)
@app.get("/")
async def get_chat():
response = FileResponse(EXPERT_DIR / "static" / "index.html")
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
return response
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket endpoint for chat."""
await websocket.accept()
thread_id = f"web-{id(websocket)}"
printed_count = 0
try:
while True:
data = await websocket.receive_text()
message_data = json.loads(data)
user_message = message_data.get("message", "")
if not user_message:
continue
printed_count = 0
try:
async for chunk in agent.astream(
{"messages": [("user", user_message)]},
config={"configurable": {"thread_id": thread_id}},
stream_mode="values",
):
if "messages" in chunk:
messages = chunk["messages"]
for msg in messages[printed_count:]:
if isinstance(msg, AIMessage):
content = get_content_as_string(msg.content)
if content and content.strip():
await websocket.send_json({
"type": "assistant",
"content": content,
})
if msg.tool_calls:
for tc in msg.tool_calls:
name = tc.get("name", "unknown")
args = tc.get("args", {})
icon, status = get_tool_display(name, args)
await websocket.send_json({
"type": "tool_call",
"name": name,
"icon": icon,
"status": status,
})
elif isinstance(msg, ToolMessage):
content = get_content_as_string(msg.content)
success = not (
content and "error" in content.lower()[:100]
)
await websocket.send_json({
"type": "tool_result",
"name": getattr(msg, "name", ""),
"success": success,
})
printed_count = len(messages)
await websocket.send_json({"type": "done"})
except Exception as e:
await websocket.send_json({
"type": "error",
"message": str(e),
})
except WebSocketDisconnect:
print(f"Client disconnected: {thread_id}")
# โโโ Entry Point โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
import uvicorn
api_key = os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY")
if not api_key:
print("Error: Please set OPENROUTER_API_KEY or OPENAI_API_KEY")
sys.exit(1)
model_name = os.environ.get("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250514")
base_url = os.environ.get("LLM_BASE_URL", "https://openrouter.ai/api/v1")
subagent_model = os.environ.get("LLM_SUBAGENT_MODEL", "anthropic/claude-haiku-4-5-20251001")
print()
print("=== Code Hack AI Expert - Web Interface ===")
print(f" Model: {model_name}")
print(f" Subagent: {subagent_model}")
print(f" Base URL: {base_url}")
print(f" MCP Servers: {len(MCP_SERVERS)} (including mermaid-chart)")
print()
uvicorn.run(app, host="0.0.0.0", port=8000)