Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7674729804 | ||
|
|
11b80b90f4 | ||
|
|
71a6403e5b | ||
|
|
5def2697de | ||
|
|
612ce37518 | ||
|
|
d55a496ff4 | ||
|
|
72d6f9ab66 | ||
|
|
79c27795a8 | ||
|
|
c716dab851 |
No files matched your search
@@ -654,3 +654,131 @@ async def set_agent_orchestration(
|
||||
agent.orchestration = og
|
||||
db.commit()
|
||||
return {"agent_id": agent_id, "orchestration": agent.orchestration, "updated": True}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Phase 4.2: YAML workflow import/export/validate/templates
|
||||
# ============================================================
|
||||
|
||||
import yaml as _yaml
|
||||
import os as _os
|
||||
from app.core.yaml_workflow import validate_yaml, yaml_to_orchestration, orchestration_to_yaml
|
||||
from app.core.orchestrator import validate_graph
|
||||
|
||||
_YTMPL = _os.path.join(_os.path.dirname(_os.path.dirname(_os.path.dirname(__file__))), "workflow_templates")
|
||||
|
||||
|
||||
class YAMLBody(BaseModel):
|
||||
yaml_text: str
|
||||
|
||||
|
||||
@router.post("/orchestration/yaml/validate", summary="校验 YAML 工作流")
|
||||
async def yaml_validate(req: YAMLBody, admin_user=Depends(get_current_admin)):
|
||||
try:
|
||||
data = _yaml.safe_load(req.yaml_text)
|
||||
except _yaml.YAMLError as e:
|
||||
return {"ok": False, "errors": [f"YAML parse: {str(e)}"], "warnings": []}
|
||||
r = validate_yaml(data)
|
||||
if r["ok"]:
|
||||
try:
|
||||
validate_graph(yaml_to_orchestration(data))
|
||||
except Exception as e:
|
||||
r["ok"] = False; r["errors"].append(f"Graph fail: {str(e)}")
|
||||
return r
|
||||
|
||||
|
||||
@router.post("/{agent_id}/orchestration/yaml/import", summary="YAML 导入编排")
|
||||
async def yaml_import(agent_id: str, req: YAMLBody, admin_user=Depends(get_current_admin), db=Depends(get_db)):
|
||||
ag = db.query(MarketApp).filter(MarketApp.id == agent_id, MarketApp.type == "agent").first()
|
||||
if not ag:
|
||||
raise HTTPException(status_code=404, detail="Agent not found")
|
||||
try:
|
||||
data = _yaml.safe_load(req.yaml_text)
|
||||
except _yaml.YAMLError as e:
|
||||
raise HTTPException(status_code=400, detail=f"YAML parse: {str(e)}")
|
||||
v = validate_yaml(data)
|
||||
if not v["ok"]:
|
||||
raise HTTPException(status_code=400, detail="YAML invalid: " + "; ".join(v["errors"]))
|
||||
orch = yaml_to_orchestration(data)
|
||||
try:
|
||||
validate_graph(orch)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail=f"Graph invalid: {str(e)}")
|
||||
ag.orchestration = orch
|
||||
ag.updated_at = datetime.now()
|
||||
db.commit()
|
||||
return {"agent_id": agent_id, "orchestration": ag.orchestration, "imported": True}
|
||||
|
||||
|
||||
@router.post("/{agent_id}/orchestration/yaml/export", summary="编排导出 YAML")
|
||||
async def yaml_export(agent_id: str, admin_user=Depends(get_current_admin), db=Depends(get_db)):
|
||||
ag = db.query(MarketApp).filter(MarketApp.id == agent_id, MarketApp.type == "agent").first()
|
||||
if not ag:
|
||||
raise HTTPException(status_code=404, detail="Agent not found")
|
||||
if not ag.orchestration:
|
||||
raise HTTPException(status_code=400, detail="No orchestration")
|
||||
yaml_str = _yaml.dump(orchestration_to_yaml(ag.orchestration), allow_unicode=True, default_flow_style=False, sort_keys=False)
|
||||
return {"agent_id": agent_id, "yaml": yaml_str, "version": "1.0"}
|
||||
|
||||
|
||||
@router.get("/orchestration/yaml/templates", summary="内置模板")
|
||||
async def yaml_templates(admin_user=Depends(get_current_admin)):
|
||||
tmpls = []
|
||||
if _os.path.isdir(_YTMPL):
|
||||
for fp in sorted(_os.listdir(_YTMPL)):
|
||||
if fp.endswith((".yaml", ".yml")):
|
||||
try:
|
||||
with open(_os.path.join(_YTMPL, fp), encoding="utf-8") as f:
|
||||
txt = f.read()
|
||||
d = _yaml.safe_load(txt) or {}
|
||||
tmpls.append({"filename": fp, "name": d.get("name", fp),
|
||||
"description": d.get("description", ""),
|
||||
"category": d.get("category", "general"), "yaml": txt})
|
||||
except Exception:
|
||||
tmpls.append({"filename": fp, "name": fp, "error": True})
|
||||
return {"templates": tmpls, "count": len(tmpls)}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Phase 4.3: ACA 协议抽象 — protocols / tools / health
|
||||
# ============================================================
|
||||
|
||||
from app.core.aca import registry as _aca_registry, init_aca_registry
|
||||
|
||||
# 懒初始化:首次调用 ACA 端点时确保 registry 已填充
|
||||
_aca_initialized = False
|
||||
|
||||
def _ensure_aca():
|
||||
global _aca_initialized
|
||||
if not _aca_initialized:
|
||||
init_aca_registry()
|
||||
_aca_initialized = True
|
||||
|
||||
|
||||
@router.get("/aca/protocols", summary="ACA 已注册协议")
|
||||
async def aca_protocols(admin_user=Depends(get_current_admin)):
|
||||
_ensure_aca()
|
||||
return [
|
||||
{"name": a.name, "version": a.version, "capabilities": a.capabilities}
|
||||
for a in _aca_registry.list_all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/aca/protocols/{name}/tools", summary="协议工具列表")
|
||||
async def aca_protocol_tools(name: str, admin_user=Depends(get_current_admin)):
|
||||
_ensure_aca()
|
||||
adapter = _aca_registry.get(name)
|
||||
if not adapter:
|
||||
raise HTTPException(status_code=404, detail=f"协议 {name} 未注册")
|
||||
tools = await adapter.list_tools()
|
||||
return {"protocol": name, "tools": tools, "count": len(tools)}
|
||||
|
||||
|
||||
@router.post("/aca/protocols/{name}/health", summary="协议健康检查")
|
||||
async def aca_protocol_health(name: str, admin_user=Depends(get_current_admin)):
|
||||
_ensure_aca()
|
||||
adapter = _aca_registry.get(name)
|
||||
if not adapter:
|
||||
raise HTTPException(status_code=404, detail=f"协议 {name} 未注册")
|
||||
ok = await adapter.health_check()
|
||||
return {"protocol": name, "healthy": ok}
|
||||
@@ -183,6 +183,11 @@ async def get_all_apps(
|
||||
"install_count": a.install_count,
|
||||
"created_at": a.created_at.isoformat() if a.created_at else None,
|
||||
"updated_at": a.updated_at.isoformat() if a.updated_at else None,
|
||||
# Phase 4.1: 安检/版本化/绿标
|
||||
"version": a.version or "1.0.0",
|
||||
"security_scan": a.security_scan,
|
||||
"verified": bool(a.verified),
|
||||
"dependencies": a.dependencies,
|
||||
}
|
||||
for a in apps
|
||||
],
|
||||
|
||||
@@ -1430,7 +1430,7 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
|
||||
logger.info(f"[_generate_media_task] 启动 media 生成 msg={ai_msg_id} model={ai_model_id} prompt={prompt[:60]!r}")
|
||||
caps = [c.lower() for c in (ai_model.capabilities or [])]
|
||||
is_video = "video" in caps
|
||||
timeout_seconds = 300 if is_video else 90
|
||||
timeout_seconds = 300 if is_video else 180
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
_generate_media(db, ai_model, prompt, user_id),
|
||||
|
||||
@@ -1657,6 +1657,16 @@ async def _send_message_core(
|
||||
|
||||
|
||||
|
||||
# 媒体分支直接返回,不会进入 LLM 工具调用;提前初始化避免未绑定
|
||||
|
||||
called_skill_names = []
|
||||
|
||||
|
||||
|
||||
called_mcp_names = []
|
||||
|
||||
|
||||
|
||||
if effective_skill_ids:
|
||||
|
||||
|
||||
|
||||
@@ -128,7 +128,15 @@ def setup_file_logging():
|
||||
root_logger.setLevel(logging.INFO)
|
||||
root_logger.addHandler(app_handler)
|
||||
root_logger.addHandler(error_handler)
|
||||
root_logger.addFilter(TraceIdFilter())
|
||||
|
||||
# TraceIdFilter 必须挂在 handler 上,而非 root logger。
|
||||
# logger 级 filter 只对「直接经该 logger 发射」的记录生效;子 logger 的记录向上冒泡
|
||||
# 到 root 的 handler 时不会经过 root 的 logger 级 filter,导致 %(trace_id)s 缺失并抛
|
||||
# KeyError('trace_id')。handler 级 filter 对经它格式化的每条记录都生效。
|
||||
_tid_filter = TraceIdFilter()
|
||||
app_handler.addFilter(_tid_filter)
|
||||
error_handler.addFilter(_tid_filter)
|
||||
access_handler.addFilter(_tid_filter)
|
||||
|
||||
# 配置访问日志专用logger
|
||||
access_logger = logging.getLogger("aiflow.access")
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
"""Phase 4.3: ACA (Agent Communication Abstraction) 协议抽象层.
|
||||
|
||||
设计目标:
|
||||
- 定义统一对外工具协议接口,隔离 MCP / A2A / 自定义协议的具体实现。
|
||||
- 防止协议绑架:未来 MCP 升级或 A2A 替代 MCP 时,只需增删适配器,不改业务代码。
|
||||
- 每个协议适配器被注册为 "protocol adapter",按名称发现。
|
||||
|
||||
接口:
|
||||
ACAProtocol
|
||||
name: str
|
||||
version: str
|
||||
capabilities: list[str]
|
||||
async list_tools() -> list[dict] # [{name, description, inputSchema}]
|
||||
async call_tool(tool_name, arguments) -> str
|
||||
async health_check() -> bool
|
||||
|
||||
ProtocolRegistry
|
||||
register(adapter: ACAProtocol)
|
||||
get(name: str) -> ACAProtocol
|
||||
list_all() -> list[ACAProtocol]
|
||||
async list_all_tools() -> list[dict] # 聚合所有协议的 tools,带 protocol tag
|
||||
async call_tool(protocol_name, tool_name, args) -> str
|
||||
|
||||
使用示例:
|
||||
from app.core.aca import registry
|
||||
tools = await registry.list_all_tools()
|
||||
# tools: [{"name":"search","protocol":"mcp","description":"..."}, ...]
|
||||
result = await registry.call_tool("mcp", "search", {"query":"..."})
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger("aiflow.aca")
|
||||
|
||||
# ── 协议接口 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
class ACAProtocol(abc.ABC):
|
||||
name: str = ""
|
||||
version: str = "1.0"
|
||||
capabilities: list[str] = []
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_tools(self) -> list[dict]:
|
||||
"""返回 [{name, description, inputSchema}]。"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def call_tool(self, tool_name: str, arguments: dict) -> str:
|
||||
"""调用工具并返回文本结果。"""
|
||||
|
||||
async def health_check(self) -> bool:
|
||||
"""健康检查,默认 True。"""
|
||||
return True
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ACA {self.name} v{self.version}>"
|
||||
|
||||
|
||||
# ── 注册表 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
class ProtocolRegistry:
|
||||
"""全局协议注册表,单例。"""
|
||||
|
||||
def __init__(self):
|
||||
self._adapters: dict[str, ACAProtocol] = {}
|
||||
|
||||
def register(self, adapter: ACAProtocol):
|
||||
if not adapter.name:
|
||||
raise ValueError("protocol adapter must have a name")
|
||||
self._adapters[adapter.name] = adapter
|
||||
logger.info("ACA registry: registered %s", adapter)
|
||||
|
||||
def get(self, name: str) -> ACAProtocol | None:
|
||||
return self._adapters.get(name)
|
||||
|
||||
def list_all(self) -> list[ACAProtocol]:
|
||||
return list(self._adapters.values())
|
||||
|
||||
async def list_all_tools(self) -> list[dict]:
|
||||
"""聚合所有已注册协议的 tools,每个 tool 标记 protocol。"""
|
||||
tasks = [self._list_with_name(a) for a in self._adapters.values()]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
flat: list[dict] = []
|
||||
for rlist in results:
|
||||
if isinstance(rlist, list):
|
||||
flat.extend(rlist)
|
||||
return flat
|
||||
|
||||
async def _list_with_name(self, adapter: ACAProtocol) -> list[dict]:
|
||||
try:
|
||||
tools = await adapter.list_tools()
|
||||
for t in tools:
|
||||
t["protocol"] = adapter.name
|
||||
return tools
|
||||
except Exception as e:
|
||||
logger.warning("ACA: list_tools failed for %s: %s", adapter.name, e)
|
||||
return []
|
||||
|
||||
async def call_tool(self, protocol_name: str, tool_name: str, arguments: dict) -> str:
|
||||
adapter = self._adapters.get(protocol_name)
|
||||
if not adapter:
|
||||
raise ValueError(f"协议 {protocol_name} 未注册")
|
||||
return await adapter.call_tool(tool_name, arguments)
|
||||
|
||||
|
||||
# 全局单例
|
||||
registry = ProtocolRegistry()
|
||||
|
||||
|
||||
# ── MCP 适配器 ───────────────────────────────────────────────────────────────
|
||||
|
||||
class McpProtocolAdapter(ACAProtocol):
|
||||
"""包装平台现有的 MCP 客户端 (app.mcp_client),提供统一协议接口。"""
|
||||
|
||||
def __init__(self, server_configs: list[dict] = None):
|
||||
self.name = "mcp"
|
||||
self.version = "1.0"
|
||||
self.capabilities = ["tools", "resources", "prompts"]
|
||||
self._server_configs = server_configs or []
|
||||
self._tools_cache: list[dict] = []
|
||||
self._cache_ts: float = 0
|
||||
|
||||
async def list_tools(self) -> list[dict]:
|
||||
# Use cached tools if available (TTL 30s)
|
||||
import time
|
||||
if self._tools_cache and (time.time() - self._cache_ts) < 30:
|
||||
return [dict(t) for t in self._tools_cache]
|
||||
from app.mcp_client import list_mcp_tools
|
||||
all_tools: list[dict] = []
|
||||
for server in self._server_configs:
|
||||
try:
|
||||
tools = await list_mcp_tools(server)
|
||||
for t in tools:
|
||||
t["_mcp_server_id"] = server.get("id", "")
|
||||
t["_mcp_server_name"] = server.get("name", "")
|
||||
all_tools.extend(tools)
|
||||
except Exception as e:
|
||||
logger.warning("MCP list_tools failed for %s: %s", server.get("name"), e)
|
||||
self._tools_cache = [dict(t) for t in all_tools]
|
||||
self._cache_ts = time.time()
|
||||
return list(self._tools_cache)
|
||||
|
||||
async def call_tool(self, tool_name: str, arguments: dict) -> str:
|
||||
from app.mcp_client import call_mcp_tool
|
||||
# Find the server that has this tool (check cache first)
|
||||
for t in self._tools_cache:
|
||||
if t.get("name") == tool_name:
|
||||
sid = t.get("_mcp_server_id", "")
|
||||
server = next((s for s in self._server_configs if s.get("id") == sid), None)
|
||||
if server:
|
||||
return await call_mcp_tool(server, tool_name, arguments)
|
||||
# Fallback: try first available server
|
||||
if self._server_configs:
|
||||
return await call_mcp_tool(self._server_configs[0], tool_name, arguments)
|
||||
return json.dumps({"error": "No MCP server configured for tool: " + tool_name})
|
||||
|
||||
async def health_check(self) -> bool:
|
||||
# Check if any MCP server is connected
|
||||
try:
|
||||
tools = await self.list_tools()
|
||||
return len(tools) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ── A2A 适配器 ───────────────────────────────────────────────────────────────
|
||||
|
||||
class A2aProtocolAdapter(ACAProtocol):
|
||||
"""A2A (Agent-to-Agent) 协议适配器。
|
||||
|
||||
通过标准 JSON-RPC 与远端 Agent 通信。端点需实现:
|
||||
- POST /a2a/tools → 返回工具列表
|
||||
- POST /a2a/call → 调用工具
|
||||
|
||||
A2A 规范参考: agentcommunicationprotocol.dev
|
||||
"""
|
||||
|
||||
def __init__(self, endpoint: str, api_key: str = None, timeout: float = 30):
|
||||
self.name = "a2a"
|
||||
self.version = "0.9"
|
||||
self.capabilities = ["tools"]
|
||||
self.endpoint = endpoint.rstrip("/")
|
||||
self.api_key = api_key
|
||||
self.timeout = timeout
|
||||
|
||||
async def list_tools(self) -> list[dict]:
|
||||
async with httpx.AsyncClient(timeout=self.timeout, trust_env=False) as client:
|
||||
headers = self._headers()
|
||||
resp = await client.post(f"{self.endpoint}/a2a/tools", headers=headers, json={})
|
||||
if resp.status_code != 200:
|
||||
logger.warning("A2A list_tools %s HTTP %s: %s", self.endpoint, resp.status_code, resp.text[:200])
|
||||
return []
|
||||
data = resp.json()
|
||||
return data.get("tools") or data.get("data", {}).get("tools") or []
|
||||
|
||||
async def call_tool(self, tool_name: str, arguments: dict) -> str:
|
||||
async with httpx.AsyncClient(timeout=self.timeout, trust_env=False) as client:
|
||||
headers = self._headers()
|
||||
body = {
|
||||
"jsonrpc": "2.0",
|
||||
"method": "tools/call",
|
||||
"params": {"name": tool_name, "arguments": arguments},
|
||||
"id": 1,
|
||||
}
|
||||
resp = await client.post(f"{self.endpoint}/a2a/call", headers=headers, json=body)
|
||||
if resp.status_code != 200:
|
||||
return json.dumps({"error": f"A2A HTTP {resp.status_code}: {resp.text[:300]}"})
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
return json.dumps({"error": data["error"]})
|
||||
result = data.get("result")
|
||||
if isinstance(result, dict):
|
||||
return result.get("content", json.dumps(result))
|
||||
return str(result) if result is not None else ""
|
||||
|
||||
async def health_check(self) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10, trust_env=False) as client:
|
||||
headers = self._headers()
|
||||
resp = await client.get(f"{self.endpoint}/a2a/health", headers=headers)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _headers(self) -> dict:
|
||||
h = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
h["Authorization"] = f"Bearer {self.api_key}"
|
||||
return h
|
||||
|
||||
|
||||
# ── 启动时初始化 ─────────────────────────────────────────────────────────────
|
||||
|
||||
def init_aca_registry():
|
||||
"""在应用启动时调用,注册所有协议适配器到全局 registry。"""
|
||||
from app.database import SessionLocal
|
||||
from app.models import MCPServer
|
||||
|
||||
# 注册 MCP 适配器(从 DB 读取所有 enabled MCP server 配置)
|
||||
try:
|
||||
db = SessionLocal()
|
||||
servers = db.query(MCPServer).filter(MCPServer.is_enabled == True).all()
|
||||
server_configs = []
|
||||
for s in servers:
|
||||
server_configs.append({
|
||||
"id": s.id,
|
||||
"name": s.name,
|
||||
"transport_type": s.transport_type,
|
||||
"command": s.command,
|
||||
"args": json.loads(s.args) if isinstance(s.args, str) else s.args or [],
|
||||
"env_vars": json.loads(s.env_vars) if isinstance(s.env_vars, str) else s.env_vars or {},
|
||||
"url": s.url,
|
||||
"headers": json.loads(s.headers) if isinstance(s.headers, str) else s.headers or {},
|
||||
})
|
||||
db.close()
|
||||
if server_configs:
|
||||
registry.register(McpProtocolAdapter(server_configs))
|
||||
logger.info("ACA: MCP adapter registered with %d servers", len(server_configs))
|
||||
except Exception as e:
|
||||
logger.warning("ACA: failed to init MCP adapter: %s", e)
|
||||
|
||||
# 注册 A2A 适配器(从配置或 DB 读取 A2A endpoint)
|
||||
# A2A endpoint 可以从 site_settings 读取,暂无则留空(以后台配置驱动)
|
||||
a2a_endpoint = _get_a2a_config()
|
||||
if a2a_endpoint:
|
||||
registry.register(A2aProtocolAdapter(
|
||||
endpoint=a2a_endpoint.get("endpoint", ""),
|
||||
api_key=a2a_endpoint.get("api_key"),
|
||||
))
|
||||
logger.info("ACA: A2A adapter registered at %s", a2a_endpoint.get("endpoint"))
|
||||
|
||||
|
||||
def _get_a2a_config() -> dict | None:
|
||||
"""从 site_settings 读取 A2A 全局配置。"""
|
||||
try:
|
||||
from app.database import SessionLocal
|
||||
from app.models import SiteSetting
|
||||
db = SessionLocal()
|
||||
setting = db.query(SiteSetting).filter(SiteSetting.key == "aca_a2a_endpoint").first()
|
||||
db.close()
|
||||
if setting and setting.value:
|
||||
val = json.loads(setting.value) if isinstance(setting.value, str) else setting.value
|
||||
if isinstance(val, dict) and val.get("endpoint"):
|
||||
return val
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Phase 4.2: QihuFlow 工作流可移植描述语言 (YAML v1.0)
|
||||
|
||||
提供 YAML 工作流文本 ↔ orchestrator JSON 的双向转换与校验。
|
||||
|
||||
YAML 规范 v1.0 示例:
|
||||
|
||||
version: "1.0"
|
||||
name: "Research & Code"
|
||||
description: "Research then generate code"
|
||||
output_node: merge
|
||||
|
||||
nodes:
|
||||
- id: research
|
||||
type: llm
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a researcher."
|
||||
- id: coder
|
||||
type: local
|
||||
agent_id: "uuid-here"
|
||||
config:
|
||||
skill_ids: ["search", "code-run"]
|
||||
- id: merge
|
||||
type: reduce
|
||||
config:
|
||||
strategy: concat
|
||||
|
||||
edges:
|
||||
- from: research
|
||||
to: coder
|
||||
- from: coder
|
||||
to: merge
|
||||
|
||||
config 字段映射(YAML config ↔ orchestrator JSON):
|
||||
|
||||
YAML config key JSON field
|
||||
─────────────────────────────────────────────
|
||||
model model_id
|
||||
system_prompt system_prompt
|
||||
skill_ids skill_ids
|
||||
knowledge_base_ids knowledge_base_ids
|
||||
endpoint agent_endpoint
|
||||
api_key api_key
|
||||
strategy strategy (reduce)
|
||||
max_tokens max_tokens
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
SPEC_VERSION = "1.0"
|
||||
|
||||
# YAML config → JSON field mapping
|
||||
_CONFIG_MAP = {
|
||||
"model": "model_id",
|
||||
"system_prompt": "system_prompt",
|
||||
"skill_ids": "skill_ids",
|
||||
"knowledge_base_ids": "knowledge_base_ids",
|
||||
"endpoint": "agent_endpoint",
|
||||
"api_key": "api_key",
|
||||
"strategy": "strategy",
|
||||
"max_tokens": "max_tokens",
|
||||
"description": "description",
|
||||
}
|
||||
|
||||
# reverse map: JSON → YAML config keys to nest
|
||||
_REVERSE_CONFIG = {
|
||||
"model_id", "system_prompt", "skill_ids", "knowledge_base_ids",
|
||||
"agent_endpoint", "api_key", "strategy", "max_tokens",
|
||||
}
|
||||
|
||||
VALID_NODE_TYPES = {"llm", "local", "external", "reduce"}
|
||||
VALID_ON_ERROR = {"halt", "continue"}
|
||||
VALID_REDUCE_STRATEGY = {"concat", "first", "last"}
|
||||
|
||||
|
||||
# ── validation ──────────────────────────────────────────────────────────────
|
||||
|
||||
def validate_yaml(data: Any) -> dict:
|
||||
"""校验 YAML 工作流结构,返回 {ok, errors:[...], warnings:[...]}。
|
||||
|
||||
data 应为解析后的 YAML 字典(由调用方用 yaml.safe_load 解析)。
|
||||
"""
|
||||
errors: list = []
|
||||
warnings: list = []
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return {"ok": False, "errors": ["YAML 顶层必须为对象"], "warnings": []}
|
||||
|
||||
version = data.get("version")
|
||||
if not version or version != SPEC_VERSION:
|
||||
warnings.append(f"version 应为 \"{SPEC_VERSION}\",当前为 \"{version}\"")
|
||||
|
||||
nodes = data.get("nodes")
|
||||
if not isinstance(nodes, list) or not nodes:
|
||||
errors.append("nodes 必须为非空数组")
|
||||
return {"ok": False, "errors": errors, "warnings": warnings}
|
||||
|
||||
node_ids: set = set()
|
||||
for i, node in enumerate(nodes):
|
||||
if not isinstance(node, dict):
|
||||
errors.append(f"节点 #{i} 必须为对象")
|
||||
continue
|
||||
nid = node.get("id")
|
||||
if not nid or not isinstance(nid, str):
|
||||
errors.append(f"节点 #{i} 缺少字符串 id")
|
||||
continue
|
||||
if nid in node_ids:
|
||||
errors.append(f"节点 id 重复: {nid}")
|
||||
node_ids.add(nid)
|
||||
|
||||
ntype = node.get("type")
|
||||
if ntype not in VALID_NODE_TYPES:
|
||||
errors.append(f"节点 {nid} 类型非法: {ntype} (允许 {', '.join(sorted(VALID_NODE_TYPES))})")
|
||||
|
||||
on_error = node.get("on_error", "continue")
|
||||
if on_error and on_error not in VALID_ON_ERROR:
|
||||
errors.append(f"节点 {nid} on_error 非法: {on_error}")
|
||||
|
||||
# type-specific checks
|
||||
if ntype in ("local", "external"):
|
||||
if not node.get("agent_id"):
|
||||
errors.append(f"节点 {nid} 类型 {ntype} 必须指定 agent_id")
|
||||
|
||||
# config validation
|
||||
cfg = node.get("config", {})
|
||||
if isinstance(cfg, dict):
|
||||
strategy = cfg.get("strategy")
|
||||
if strategy and strategy not in VALID_REDUCE_STRATEGY:
|
||||
errors.append(f"节点 {nid} config.strategy 非法: {strategy}")
|
||||
|
||||
edges = data.get("edges", [])
|
||||
if not isinstance(edges, list):
|
||||
errors.append("edges 必须为数组")
|
||||
else:
|
||||
for i, edge in enumerate(edges):
|
||||
if not isinstance(edge, dict):
|
||||
errors.append(f"边 #{i} 必须为对象")
|
||||
continue
|
||||
f = edge.get("from")
|
||||
t = edge.get("to")
|
||||
if not f or not t:
|
||||
errors.append(f"边 #{i} 缺少 from/to")
|
||||
if f and f not in node_ids:
|
||||
errors.append(f"边 #{i} from={f} 指向不存在的节点")
|
||||
if t and t not in node_ids:
|
||||
errors.append(f"边 #{i} to={t} 指向不存在的节点")
|
||||
if f and t and f == t:
|
||||
errors.append(f"边 #{i} 存在自环: {f}")
|
||||
|
||||
output_node = data.get("output_node")
|
||||
if output_node and output_node not in node_ids:
|
||||
warnings.append(f"output_node={output_node} 不存在于节点列表中,将自动检测出度为零的节点")
|
||||
|
||||
# cycle detection (topological sort)
|
||||
if node_ids and not errors:
|
||||
indeg = {nid: 0 for nid in node_ids}
|
||||
adj = {nid: [] for nid in node_ids}
|
||||
for e in edges:
|
||||
if isinstance(e, dict):
|
||||
f, t = e.get("from"), e.get("to")
|
||||
if f in adj and t in adj:
|
||||
adj[f].append(t)
|
||||
indeg[t] += 1
|
||||
queue = [nid for nid in node_ids if indeg[nid] == 0]
|
||||
processed = 0
|
||||
while queue:
|
||||
n = queue.pop(0)
|
||||
processed += 1
|
||||
for nxt in adj[n]:
|
||||
indeg[nxt] -= 1
|
||||
if indeg[nxt] == 0:
|
||||
queue.append(nxt)
|
||||
if processed != len(node_ids):
|
||||
errors.append("检测到环路,无法进行拓扑排序")
|
||||
|
||||
return {
|
||||
"ok": len(errors) == 0,
|
||||
"errors": errors,
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
|
||||
# ── YAML → orchestrator JSON ─────────────────────────────────────────────────
|
||||
|
||||
def yaml_to_orchestration(data: dict) -> dict:
|
||||
"""将 YAML 工作流对象转换为 orchestrator.run_graph() 接受的 JSON 格式。"""
|
||||
result: dict = {"nodes": [], "edges": []}
|
||||
|
||||
result["name"] = data.get("name")
|
||||
result["description"] = data.get("description")
|
||||
if data.get("output_node"):
|
||||
result["output_node"] = data["output_node"]
|
||||
|
||||
for raw_node in data.get("nodes", []):
|
||||
if not isinstance(raw_node, dict):
|
||||
continue
|
||||
node: dict = {
|
||||
"id": raw_node.get("id", ""),
|
||||
"type": raw_node.get("type", "llm"),
|
||||
"description": raw_node.get("description", ""),
|
||||
"on_error": raw_node.get("on_error", "continue"),
|
||||
}
|
||||
|
||||
# agent_id for local/external
|
||||
if raw_node.get("agent_id"):
|
||||
node["agent_id"] = raw_node["agent_id"]
|
||||
|
||||
# flatten config into top-level keys
|
||||
config = raw_node.get("config", {})
|
||||
if isinstance(config, dict):
|
||||
for yaml_key, json_key in _CONFIG_MAP.items():
|
||||
if yaml_key in config and config[yaml_key] is not None:
|
||||
node[json_key] = config[yaml_key]
|
||||
|
||||
# also carry over any extra keys from raw_node (preserve flexibility)
|
||||
for k, v in raw_node.items():
|
||||
if k not in ("id", "type", "config", "description", "on_error", "agent_id"):
|
||||
if k in ("skill_ids", "knowledge_base_ids", "model_id", "system_prompt",
|
||||
"agent_endpoint", "api_key", "strategy", "max_tokens"):
|
||||
node[k] = v
|
||||
|
||||
result["nodes"].append(node)
|
||||
|
||||
for edge in data.get("edges", []):
|
||||
if isinstance(edge, dict):
|
||||
result["edges"].append({
|
||||
"from": edge.get("from", ""),
|
||||
"to": edge.get("to", ""),
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ── orchestrator JSON → YAML ─────────────────────────────────────────────────
|
||||
|
||||
def orchestration_to_yaml(data: dict) -> dict:
|
||||
"""将 orchestrator JSON 转换为 YAML 规范对象(可再 yaml.dump 输出)。"""
|
||||
result: dict = {"version": SPEC_VERSION}
|
||||
|
||||
if data.get("name"):
|
||||
result["name"] = data["name"]
|
||||
if data.get("description"):
|
||||
result["description"] = data["description"]
|
||||
if data.get("output_node"):
|
||||
result["output_node"] = data["output_node"]
|
||||
|
||||
result["nodes"] = []
|
||||
for json_node in data.get("nodes", []):
|
||||
if not isinstance(json_node, dict):
|
||||
continue
|
||||
node: dict = {
|
||||
"id": json_node.get("id", ""),
|
||||
"type": json_node.get("type", "llm"),
|
||||
}
|
||||
if json_node.get("description"):
|
||||
node["description"] = json_node["description"]
|
||||
if json_node.get("on_error"):
|
||||
node["on_error"] = json_node["on_error"]
|
||||
if json_node.get("agent_id"):
|
||||
node["agent_id"] = json_node["agent_id"]
|
||||
|
||||
# nest known config keys into config sub-object
|
||||
config: dict = {}
|
||||
for yaml_key, json_key in _CONFIG_MAP.items():
|
||||
if json_key in json_node and json_node[json_key] is not None:
|
||||
config[yaml_key] = json_node[json_key]
|
||||
|
||||
# also preserve any extra keys not in the map
|
||||
for k, v in json_node.items():
|
||||
if k not in ("id", "type", "description", "on_error", "agent_id") \
|
||||
and k not in _REVERSE_CONFIG:
|
||||
if v is not None:
|
||||
config[k] = v
|
||||
|
||||
if config:
|
||||
node["config"] = config
|
||||
|
||||
result["nodes"].append(node)
|
||||
|
||||
result["edges"] = []
|
||||
for edge in data.get("edges", []):
|
||||
if isinstance(edge, dict):
|
||||
result["edges"].append({
|
||||
"from": edge.get("from", ""),
|
||||
"to": edge.get("to", ""),
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ── YAML 模板参数替换 ────────────────────────────────────────────────────────
|
||||
|
||||
def apply_template_params(yaml_text: str, params: dict) -> str:
|
||||
"""替换 YAML 模板中的 ${param} 占位符。"""
|
||||
def _replacer(m: re.Match) -> str:
|
||||
key = m.group(1)
|
||||
return str(params.get(key, m.group(0)))
|
||||
return re.sub(r"\$\{(\w+)\}", _replacer, yaml_text)
|
||||
+1159
-1159
File diff suppressed because it is too large.
Load diff
@@ -96,10 +96,24 @@ class PipelineScheduler:
|
||||
self._process_trajectory(db, traj)
|
||||
except Exception as e:
|
||||
logger.error(f"处理轨迹 {traj.id} 失败: {e}")
|
||||
traj.error_msg = str(e)[:500]
|
||||
traj.retry_count = (traj.retry_count or 0) + 1
|
||||
traj.status = "error"
|
||||
db.commit()
|
||||
# 先回滚失效事务(_process_trajectory 内 commit 失败会让 session
|
||||
# 进入 rolled-back 状态,不回滚直接再 commit 会抛 PendingRollbackError
|
||||
# 并级联到外层日志),再写错误状态。
|
||||
try:
|
||||
db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
traj.error_msg = str(e)[:500]
|
||||
traj.retry_count = (traj.retry_count or 0) + 1
|
||||
traj.status = "error"
|
||||
db.commit()
|
||||
except Exception as ce:
|
||||
logger.error(f"更新轨迹 {traj.id} 错误状态失败: {ce}")
|
||||
try:
|
||||
db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
version: "1.0"
|
||||
name: "Code Review Pipeline"
|
||||
description: "Generate code → review → merge. A standard code-review workflow."
|
||||
category: development
|
||||
|
||||
nodes:
|
||||
- id: code_gen
|
||||
type: llm
|
||||
description: "Generate code based on requirements"
|
||||
on_error: halt
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a senior software engineer. Write clean, production-ready code based on the user's requirements. Include comments and error handling."
|
||||
|
||||
- id: review
|
||||
type: llm
|
||||
description: "Review generated code for bugs and style"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a code reviewer. Analyze the provided code for bugs, style issues, performance problems, and security vulnerabilities. Provide specific, actionable feedback."
|
||||
|
||||
- id: merge
|
||||
type: reduce
|
||||
description: "Combine code with review feedback"
|
||||
config:
|
||||
strategy: concat
|
||||
|
||||
edges:
|
||||
- from: code_gen
|
||||
to: review
|
||||
- from: code_gen
|
||||
to: merge
|
||||
- from: review
|
||||
to: merge
|
||||
@@ -0,0 +1,35 @@
|
||||
version: "1.0"
|
||||
name: "Multi-Agent Debate"
|
||||
description: "Two agents debate a topic from opposing perspectives, then a judge agent synthesizes the conclusion."
|
||||
category: creativity
|
||||
|
||||
nodes:
|
||||
- id: proponent
|
||||
type: llm
|
||||
description: "Argue in favor of the proposition"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a skilled debater. Argue strongly IN FAVOR of the given proposition. Use logic, evidence, and persuasive reasoning. Be passionate but fair."
|
||||
|
||||
- id: opponent
|
||||
type: llm
|
||||
description: "Argue against the proposition"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a skilled debater. Argue strongly AGAINST the given proposition. Use logic, evidence, and persuasive reasoning to find flaws in the proponent's case."
|
||||
|
||||
- id: judge
|
||||
type: llm
|
||||
description: "Evaluate both sides and reach a conclusion"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are an impartial judge. Evaluate both arguments fairly. Identify the strongest points from each side. Provide a balanced conclusion and recommendation."
|
||||
|
||||
edges:
|
||||
- from: proponent
|
||||
to: judge
|
||||
- from: opponent
|
||||
to: judge
|
||||
@@ -0,0 +1,25 @@
|
||||
version: "1.0"
|
||||
name: "RAG Search Pipeline"
|
||||
description: "Search knowledge base → augment with context → generate answer. Standard RAG pipeline."
|
||||
category: productivity
|
||||
|
||||
nodes:
|
||||
- id: search
|
||||
type: llm
|
||||
description: "Generate search queries and retrieve relevant context"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a search specialist. For the given question, identify 2-3 key search points. Then search the provided knowledge base for relevant information. Return the most relevant passages with source references."
|
||||
|
||||
- id: answer
|
||||
type: llm
|
||||
description: "Generate final answer with citations"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a knowledge assistant. Using the search results provided, generate a comprehensive answer. Always cite your sources. If information is insufficient, clearly state what is missing."
|
||||
|
||||
edges:
|
||||
- from: search
|
||||
to: answer
|
||||
@@ -0,0 +1,25 @@
|
||||
version: "1.0"
|
||||
name: "Research & Answer"
|
||||
description: "Research topic → generate answer. Uses two LLM nodes for research and synthesis."
|
||||
category: productivity
|
||||
|
||||
nodes:
|
||||
- id: research
|
||||
type: llm
|
||||
description: "Search and gather information on the topic"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a thorough researcher. Search for key facts, data points, and relevant context about the given topic. Provide a comprehensive summary with citations."
|
||||
|
||||
- id: answer
|
||||
type: llm
|
||||
description: "Synthesize research into final answer"
|
||||
on_error: continue
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a professional writer. Based on the research summary provided, craft a clear, well-structured answer for the user. Include key findings and actionable insights."
|
||||
|
||||
edges:
|
||||
- from: research
|
||||
to: answer
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Phase 4.2+4.3: YAML workflow + ACA protocol registry tests."""
|
||||
import pytest
|
||||
from app.core.yaml_workflow import validate_yaml, yaml_to_orchestration, orchestration_to_yaml
|
||||
|
||||
|
||||
# ── YAML workflow tests ──────────────────────────────────────────────────────
|
||||
|
||||
VALID_YAML = """
|
||||
version: "1.0"
|
||||
name: "Test"
|
||||
nodes:
|
||||
- id: a
|
||||
type: llm
|
||||
config:
|
||||
model: auto
|
||||
system_prompt: "You are a helper."
|
||||
- id: b
|
||||
type: llm
|
||||
- id: c
|
||||
type: reduce
|
||||
config:
|
||||
strategy: concat
|
||||
edges:
|
||||
- from: a
|
||||
to: b
|
||||
- from: b
|
||||
to: c
|
||||
- from: a
|
||||
to: c
|
||||
"""
|
||||
|
||||
|
||||
def test_validate_valid():
|
||||
import yaml
|
||||
data = yaml.safe_load(VALID_YAML)
|
||||
r = validate_yaml(data)
|
||||
assert r["ok"], r["errors"]
|
||||
assert r["errors"] == []
|
||||
|
||||
|
||||
def test_validate_invalid_type():
|
||||
import yaml
|
||||
data = yaml.safe_load("version: '1.0'\nnodes:\n - id: x\n type: bogus")
|
||||
r = validate_yaml(data)
|
||||
assert not r["ok"]
|
||||
assert any("bogus" in e for e in r["errors"])
|
||||
|
||||
|
||||
def test_validate_cycle():
|
||||
import yaml
|
||||
data = yaml.safe_load("version: '1.0'\nnodes:\n - id: a\n type: llm\n - id: b\n type: llm\nedges:\n - from: a\n to: b\n - from: b\n to: a")
|
||||
r = validate_yaml(data)
|
||||
assert not r["ok"]
|
||||
assert any("环" in e for e in r["errors"])
|
||||
|
||||
|
||||
def test_yaml_to_json_roundtrip():
|
||||
import yaml
|
||||
data = yaml.safe_load(VALID_YAML)
|
||||
orch = yaml_to_orchestration(data)
|
||||
assert len(orch["nodes"]) == 3
|
||||
assert len(orch["edges"]) == 3
|
||||
# config flattening
|
||||
node_a = next(n for n in orch["nodes"] if n["id"] == "a")
|
||||
assert node_a.get("model_id") == "auto"
|
||||
assert node_a.get("system_prompt") == "You are a helper."
|
||||
|
||||
|
||||
def test_json_to_yaml_to_json():
|
||||
"""Roundtrip: JSON → YAML obj → JSON should preserve key fields."""
|
||||
orch_json = {
|
||||
"nodes": [
|
||||
{"id": "x", "type": "llm", "model_id": "auto"},
|
||||
{"id": "y", "type": "reduce", "strategy": "concat"},
|
||||
],
|
||||
"edges": [{"from": "x", "to": "y"}],
|
||||
}
|
||||
yaml_obj = orchestration_to_yaml(orch_json)
|
||||
assert yaml_obj["version"] == "1.0"
|
||||
# config nesting
|
||||
node_x = next(n for n in yaml_obj["nodes"] if n["id"] == "x")
|
||||
assert node_x.get("config", {}).get("model") == "auto"
|
||||
node_y = next(n for n in yaml_obj["nodes"] if n["id"] == "y")
|
||||
assert node_y.get("config", {}).get("strategy") == "concat"
|
||||
|
||||
|
||||
def test_validate_missing_agent_id():
|
||||
import yaml
|
||||
data = yaml.safe_load("version: '1.0'\nnodes:\n - id: x\n type: local\n - id: y\n type: llm\nedges:\n - from: x\n to: y")
|
||||
r = validate_yaml(data)
|
||||
assert not r["ok"]
|
||||
assert any("agent_id" in e for e in r["errors"])
|
||||
@@ -894,6 +894,12 @@ export const adminAPI = {
|
||||
// Phase 3.3: 多 Agent 编排图 (orchestration)
|
||||
getAgentOrchestration: (id: string) => get<any>(`/admin/agents/${id}/orchestration`),
|
||||
setAgentOrchestration: (id: string, orchestration: any) => put<any>(`/admin/agents/${id}/orchestration`, { orchestration }),
|
||||
importYamlOrch: (id: string, yaml: string) => post<any>(`/admin/agents/${id}/orchestration/yaml/import`, { yaml_text: yaml }),
|
||||
exportYamlOrch: (id: string) => post<any>(`/admin/agents/${id}/orchestration/yaml/export`),
|
||||
getYamlTemplates: () => get<any>('/admin/agents/orchestration/yaml/templates'),
|
||||
getAcaProtocols: () => get<any>("/admin/agents/aca/protocols"),
|
||||
getAcaProtocolTools: (name: string) => get<any>(`/admin/agents/aca/protocols/${name}/tools`),
|
||||
checkAcaHealth: (name: string) => post<any>(`/admin/agents/aca/protocols/${name}/health`, {}),
|
||||
|
||||
getAdminAvailableSkills: (params?: any) => {
|
||||
|
||||
|
||||
@@ -1121,7 +1121,7 @@ const Achievement: React.FC = () => {
|
||||
|
||||
<td style={{ color: 'rgba(0,0,0,0.4)' }}>
|
||||
|
||||
{entry.last_completed ? new Date(entry.last_completed).toLocaleDateString('zh-CN') : '-'}
|
||||
{entry.last_completed ? formatBjDate(entry.last_completed) : '-'}
|
||||
|
||||
</td>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { adminAPI, marketAPI } from '@/api';
|
||||
import type { AdBanner, MarketApp } from '@/types';
|
||||
import { formatBjDate } from '@/utils/datetime';
|
||||
import './Ads.css';
|
||||
|
||||
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
|
||||
@@ -281,7 +282,7 @@ const Ads: React.FC = () => {
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ fontSize: 'var(--text-xs)', color: 'var(--color-text-tertiary)' }}>
|
||||
{new Date(banner.createdAt).toLocaleDateString()}
|
||||
{formatBjDate(banner.createdAt)}
|
||||
</td>
|
||||
<td>
|
||||
<div style={{ display: 'flex', gap: 'var(--space-xs)' }}>
|
||||
|
||||
+1015
-83
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { adminAPI } from '@/api';
|
||||
import './Apps.css';
|
||||
import { formatBjTime } from '@/utils/datetime';
|
||||
import { formatBjTime, formatBjDate } from '@/utils/datetime';
|
||||
|
||||
interface AIApp {
|
||||
id: string;
|
||||
@@ -224,11 +224,7 @@ export default function AdminApps() {
|
||||
};
|
||||
|
||||
const formatDate = (dt: string | null) => {
|
||||
if (!dt) return '-';
|
||||
try {
|
||||
const d = new Date(dt);
|
||||
return d.toLocaleDateString('zh-CN') + ' ' + d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
|
||||
} catch { return dt; }
|
||||
return formatBjTime(dt);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -738,7 +734,7 @@ function AppDetailDrawer({ app, analytics, onClose, onAction }: {
|
||||
<div key={v.id} className="version-item">
|
||||
<span className="version-num">v{v.version}</span>
|
||||
<span className="version-log">{v.changelog}</span>
|
||||
<span className="version-date">{v.created_at ? new Date(v.created_at).toLocaleDateString('zh-CN') : '-'}</span>
|
||||
<span className="version-date">{v.created_at ? formatBjDate(v.created_at) : '-'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -34,6 +34,29 @@ const styles: Record<string, React.CSSProperties> = {
|
||||
detailsGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 },
|
||||
detailsItem: { fontSize: 13 },
|
||||
detailsLabel: { color: '#6b7280', marginBottom: 4 },
|
||||
// ACA 协议抽象层 (Phase 4.3)
|
||||
acaSection: { marginTop: 32, backgroundColor: '#fff', borderRadius: 12, padding: 24, boxShadow: '0 1px 3px rgba(0,0,0,0.08)' },
|
||||
acaHead: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 },
|
||||
acaTitle: { fontSize: 18, fontWeight: 700, color: '#1A1F36' },
|
||||
acaSub: { fontSize: 13, color: '#6b7280', marginTop: 4 },
|
||||
acaRefresh: { padding: '8px 16px', border: '1px solid #e5e7eb', borderRadius: 8, cursor: 'pointer', backgroundColor: '#fff', fontSize: 13 },
|
||||
acaGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 },
|
||||
acaCard: { border: '1px solid #e5e7eb', borderRadius: 12, padding: 16 },
|
||||
acaCardTop: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' },
|
||||
acaProtoName: { fontSize: 16, fontWeight: 700, color: '#1A1F36', textTransform: 'uppercase' },
|
||||
acaVer: { fontSize: 12, color: '#9ca3af', marginLeft: 8 },
|
||||
acaCaps: { display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 },
|
||||
acaCap: { fontSize: 12, padding: '2px 8px', borderRadius: 12, backgroundColor: '#eef2ff', color: '#4338ca' },
|
||||
acaActions: { display: 'flex', gap: 8, marginTop: 14 },
|
||||
acaBtn: { padding: '6px 14px', border: '1px solid #e5e7eb', borderRadius: 6, cursor: 'pointer', backgroundColor: '#fff', fontSize: 13 },
|
||||
acaBtnPrimary: { padding: '6px 14px', border: 'none', borderRadius: 6, cursor: 'pointer', backgroundColor: '#4f46e5', color: '#fff', fontSize: 13 },
|
||||
acaHealth: { fontSize: 12, fontWeight: 600, marginTop: 10 },
|
||||
acaTools: { marginTop: 12, borderTop: '1px solid #f3f4f6', paddingTop: 12 },
|
||||
acaTool: { padding: '8px 0', borderBottom: '1px solid #f9fafb' },
|
||||
acaToolName: { fontSize: 13, fontWeight: 600, color: '#374151' },
|
||||
acaToolServer: { fontSize: 11, color: '#4f46e5', marginLeft: 8 },
|
||||
acaToolDesc: { fontSize: 12, color: '#9ca3af', marginTop: 2 },
|
||||
acaEmpty: { fontSize: 13, color: '#9ca3af', padding: '12px 0' },
|
||||
};
|
||||
|
||||
const TRANSPORT_TYPES = [
|
||||
@@ -83,6 +106,13 @@ export default function AdminMcp() {
|
||||
const [editingServer, setEditingServer] = useState<MCPServer | null>(null);
|
||||
const [toast, setToast] = useState<{ message: string; type: string } | null>(null);
|
||||
const pageSize = 20;
|
||||
// ACA 协议抽象层 (Phase 4.3)
|
||||
const [acaProtocols, setAcaProtocols] = useState<any[]>([]);
|
||||
const [acaLoading, setAcaLoading] = useState(true);
|
||||
const [acaTools, setAcaTools] = useState<Record<string, any[]>>({});
|
||||
const [acaExpanded, setAcaExpanded] = useState<Record<string, boolean>>({});
|
||||
const [acaHealth, setAcaHealth] = useState<Record<string, boolean>>({});
|
||||
const [acaChecking, setAcaChecking] = useState<Record<string, boolean>>({});
|
||||
|
||||
const showToast = (message: string, type: string = 'success') => {
|
||||
setToast({ message, type });
|
||||
@@ -119,6 +149,52 @@ export default function AdminMcp() {
|
||||
fetchStats();
|
||||
fetchServers();
|
||||
}, [fetchStats, fetchServers]);
|
||||
// ACA 协议抽象层 (Phase 4.3)
|
||||
const fetchAcaProtocols = useCallback(async () => {
|
||||
setAcaLoading(true);
|
||||
try {
|
||||
const result = await adminAPI.getAcaProtocols() as any;
|
||||
const list = Array.isArray(result) ? result : (result && result.data ? result.data : []);
|
||||
setAcaProtocols(list);
|
||||
} catch (e) {
|
||||
setAcaProtocols([]);
|
||||
} finally {
|
||||
setAcaLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchAcaTools = useCallback(async (name: string) => {
|
||||
try {
|
||||
const result = await adminAPI.getAcaProtocolTools(name) as any;
|
||||
const tools = result && result.tools ? result.tools : (result && result.data ? (result.data.tools || []) : []);
|
||||
setAcaTools(prev => ({ ...prev, [name]: tools }));
|
||||
} catch (e) {
|
||||
setAcaTools(prev => ({ ...prev, [name]: [] }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const toggleAcaTools = (name: string) => {
|
||||
setAcaExpanded(prev => {
|
||||
const next = !prev[name];
|
||||
if (next && !acaTools[name]) fetchAcaTools(name);
|
||||
return { ...prev, [name]: next };
|
||||
});
|
||||
};
|
||||
|
||||
const checkAcaHealth = async (name: string) => {
|
||||
setAcaChecking(prev => ({ ...prev, [name]: true }));
|
||||
try {
|
||||
const result = await adminAPI.checkAcaHealth(name) as any;
|
||||
const healthy = result ? (result.healthy !== undefined ? result.healthy : (result.data ? result.data.healthy : false)) : false;
|
||||
setAcaHealth(prev => ({ ...prev, [name]: healthy }));
|
||||
} catch (e) {
|
||||
setAcaHealth(prev => ({ ...prev, [name]: false }));
|
||||
} finally {
|
||||
setAcaChecking(prev => ({ ...prev, [name]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { fetchAcaProtocols(); }, [fetchAcaProtocols]);
|
||||
|
||||
const handleCreate = () => {
|
||||
setEditingServer(null);
|
||||
@@ -238,6 +314,71 @@ export default function AdminMcp() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Phase 4.3: ACA 协议抽象层 */}
|
||||
<div style={styles.acaSection}>
|
||||
<div style={styles.acaHead}>
|
||||
<div>
|
||||
<div style={styles.acaTitle}>ACA 协议抽象层</div>
|
||||
<div style={styles.acaSub}>统一协议接入(MCP / A2A / 自定义),隔离底层实现,防止协议绑架</div>
|
||||
</div>
|
||||
<button style={styles.acaRefresh} onClick={() => fetchAcaProtocols()}>刷新</button>
|
||||
</div>
|
||||
{acaLoading ? (
|
||||
<div style={styles.acaEmpty}>加载中...</div>
|
||||
) : acaProtocols.length === 0 ? (
|
||||
<div style={styles.acaEmpty}>未注册任何 ACA 协议</div>
|
||||
) : (
|
||||
<div style={styles.acaGrid}>
|
||||
{acaProtocols.map((p: any) => (
|
||||
<div key={p.name} style={styles.acaCard}>
|
||||
<div style={styles.acaCardTop}>
|
||||
<div>
|
||||
<span style={styles.acaProtoName}>{p.name}</span>
|
||||
<span style={styles.acaVer}>v{p.version}</span>
|
||||
</div>
|
||||
<span style={{ ...styles.badge, backgroundColor: '#dcfce7', color: '#166534' }}>已注册</span>
|
||||
</div>
|
||||
<div style={styles.acaCaps}>
|
||||
{(p.capabilities || []).map((c: string) => (
|
||||
<span key={c} style={styles.acaCap}>{c}</span>
|
||||
))}
|
||||
</div>
|
||||
{acaHealth[p.name] !== undefined && (
|
||||
<div style={{ ...styles.acaHealth, color: acaHealth[p.name] ? '#166534' : '#991b1b' }}>
|
||||
健康:{acaHealth[p.name] ? '正常' : '异常'}
|
||||
</div>
|
||||
)}
|
||||
<div style={styles.acaActions}>
|
||||
<button style={styles.acaBtnPrimary} onClick={() => toggleAcaTools(p.name)}>
|
||||
{acaExpanded[p.name] ? '隐藏工具' : `查看工具${acaTools[p.name] ? ' (' + acaTools[p.name].length + ')' : ''}`}
|
||||
</button>
|
||||
<button style={styles.acaBtn} disabled={acaChecking[p.name]} onClick={() => checkAcaHealth(p.name)}>
|
||||
{acaChecking[p.name] ? '检测中...' : '健康检查'}
|
||||
</button>
|
||||
</div>
|
||||
{acaExpanded[p.name] && (
|
||||
<div style={styles.acaTools}>
|
||||
{(acaTools[p.name] || []).length === 0 ? (
|
||||
<div style={styles.acaEmpty}>暂无工具</div>
|
||||
) : (
|
||||
(acaTools[p.name] || []).map((t: any, idx: number) => (
|
||||
<div key={(t.name || '') + idx} style={styles.acaTool}>
|
||||
<div>
|
||||
<span style={styles.acaToolName}>{t.name}</span>
|
||||
{t._mcp_server_name && <span style={styles.acaToolServer}>@{t._mcp_server_name}</span>}
|
||||
</div>
|
||||
{t.description && <div style={styles.acaToolDesc}>{String(t.description).substring(0, 120)}</div>}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={styles.toolbar}>
|
||||
<input
|
||||
style={styles.searchInput}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// @ts-nocheck
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { imUserAPI } from '@/api';
|
||||
import { formatBjDate } from '@/utils/datetime';
|
||||
|
||||
const PRIMARY = '#5B5FED';
|
||||
|
||||
@@ -106,7 +107,7 @@ const AppServices: React.FC = () => {
|
||||
</div>
|
||||
<p style={{ fontSize: '13px', color: '#6B7280', lineHeight: 1.7, flex: 1, margin: '0 0 14px 0' }}>{app.description || '暂无描述'}</p>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: '12px', color: '#9CA3AF' }}>{app.published_at ? '上架于 ' + new Date(app.published_at).toLocaleDateString('zh-CN') : ''}</span>
|
||||
<span style={{ fontSize: '12px', color: '#9CA3AF' }}>{app.published_at ? '上架于 ' + formatBjDate(app.published_at) : ''}</span>
|
||||
<button onClick={() => showToast('已加入「我的应用」,可在 AI 聊天中调用')} style={{ padding: '7px 16px', background: PRIMARY, border: 'none', borderRadius: '8px', color: '#fff', fontSize: '13px', fontWeight: 500, cursor: 'pointer' }}>使用</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { Asset, AssetCategory, AssetCategoryDef, AssetFileType } from '@/types';
|
||||
import { assetsAPI } from '@/api';
|
||||
import { formatBjTime } from '@/utils/datetime';
|
||||
import './AssetsPage.css';
|
||||
|
||||
const fileTypeLabels: Record<string, { label: string; bg: string; color: string }> = {
|
||||
@@ -46,7 +47,7 @@ function formatSize(bytes?: number): string {
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string): string {
|
||||
return new Date(dateStr).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||||
return formatBjTime(dateStr);
|
||||
}
|
||||
|
||||
// 将文件扩展名或API返回的file_type映射到前端fileType标签
|
||||
|
||||
+1559
-1538
File diff suppressed because it is too large.
Load diff
+1573
-1719
File diff suppressed because it is too large.
Load diff
@@ -1596,6 +1596,7 @@ const MarketPage: React.FC = () => {
|
||||
const [localApps, setLocalApps] = useState<MarketApp[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const searchTimerRef = useRef<number | null>(null);
|
||||
const [capabilityFilter, setCapabilityFilter] = useState<string | null>(null);
|
||||
const [installToast, setInstallToast] = useState<string | null>(null);
|
||||
|
||||
@@ -1893,7 +1894,7 @@ const MarketPage: React.FC = () => {
|
||||
className="form-input"
|
||||
placeholder="搜索应用名称或描述..."
|
||||
value={searchQuery}
|
||||
onChange={e => { setSearchQuery(e.target.value); loadApps(e.target.value); }}
|
||||
onChange={e => { const v = e.target.value; setSearchQuery(v); if (searchTimerRef.current) clearTimeout(searchTimerRef.current); searchTimerRef.current = window.setTimeout(() => loadApps(v), 350); }}
|
||||
style={{ paddingLeft: 32, flex: 1, maxWidth: 400 }}
|
||||
/>
|
||||
{searchQuery && (
|
||||
|
||||
@@ -7,3 +7,34 @@ export function formatBjTime(t?: string | null): string {
|
||||
if (isNaN(d.getTime())) return t;
|
||||
return d.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
|
||||
}
|
||||
|
||||
// 仅日期(北京时间)
|
||||
export function formatBjDate(t?: string | null): string {
|
||||
if (!t) return '-';
|
||||
const iso = /[Z+]/.test(t) ? t : t + '+08:00';
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return t;
|
||||
return d.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
||||
}
|
||||
|
||||
// 将任意 Date 换算为「北京墙钟」对应的 UTC 视图,便于按北京日历日比较
|
||||
function toBjView(d: Date): Date {
|
||||
return new Date(d.getTime() + (d.getTimezoneOffset() + 480) * 60000);
|
||||
}
|
||||
|
||||
// 聊天消息时间:今天 HH:MM / 昨天 HH:MM / MM-DD HH:MM / YYYY-MM-DD HH:MM(北京时间)
|
||||
export function formatChatTime(iso?: string | null): string {
|
||||
if (!iso) return '';
|
||||
const s = /[Z+]/.test(iso) ? iso : iso + '+08:00';
|
||||
const d = new Date(s);
|
||||
if (isNaN(d.getTime())) return '';
|
||||
const bj = toBjView(d);
|
||||
const nowBj = toBjView(new Date());
|
||||
const dayDiff = Math.floor(nowBj.getTime() / 86400000) - Math.floor(bj.getTime() / 86400000);
|
||||
const hhmm = d.toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit' });
|
||||
if (dayDiff <= 0) return hhmm;
|
||||
if (dayDiff === 1) return '昨天 ' + hhmm;
|
||||
const md = d.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit' });
|
||||
if (bj.getUTCFullYear() === nowBj.getUTCFullYear()) return md + ' ' + hhmm;
|
||||
return d.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }) + ' ' + hhmm;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderMarkdownToHtml } from './markdown';
|
||||
|
||||
// 前台聊天 Markdown 渲染曾两次被 bug 击穿:
|
||||
// 1) 段落内单个 \n 被转成 <br/>,导致 AI 回复被强制大量换行、内容撑成多行;
|
||||
// 2) 表格在加粗/链接转换之前被提取,单元格内 **xxx** 原样显示、且 <br> 未压缩。
|
||||
// 本测试固化「渲染管线」契约,防止回归。管线代码见 ./markdown.ts(从 ChatPage 抽出)。
|
||||
describe('renderMarkdownToHtml', () => {
|
||||
it('段落内单个 \\n 转为空格(而非 <br/>)', () => {
|
||||
const { html } = renderMarkdownToHtml('第一行\n第二行');
|
||||
expect(html).not.toContain('<br');
|
||||
expect(html).toContain('第一行 第二行');
|
||||
});
|
||||
|
||||
it('双换行转为段落分隔', () => {
|
||||
const { html } = renderMarkdownToHtml('段一\n\n段二');
|
||||
expect(html).toContain('段一</p><p class="md-p">段二');
|
||||
});
|
||||
|
||||
it('3+ 连续空行压缩为 2 个(与 2 个空行结果一致)', () => {
|
||||
const many = renderMarkdownToHtml('a\n\n\n\n\nb').html;
|
||||
const few = renderMarkdownToHtml('a\n\nb').html;
|
||||
expect(many).toBe(few);
|
||||
expect(many).toContain('a</p><p class="md-p">b');
|
||||
});
|
||||
|
||||
it('表格在加粗之后提取,单元格内的 **xxx** 被渲染为 <strong>', () => {
|
||||
const input = '| 能力 | 说明 |\n| --- | --- |\n| **渠道排序** | 按优先级 |\n';
|
||||
const { html } = renderMarkdownToHtml(input);
|
||||
expect(html).toContain('<table class="md-table">');
|
||||
expect(html).toContain('<th');
|
||||
expect(html).toContain('<td');
|
||||
expect(html).toContain('<strong>渠道排序</strong>');
|
||||
});
|
||||
|
||||
it('单元格内连续 <br> 被压缩为单个', () => {
|
||||
const input = '| 列 |\n| --- |\n| a<br/><br/>b |\n';
|
||||
const { html } = renderMarkdownToHtml(input);
|
||||
expect(html).toContain('a<br/>b');
|
||||
expect(html).not.toContain('<br/><br/>');
|
||||
});
|
||||
|
||||
it('无序列表渲染为 <ul><li>', () => {
|
||||
const { html } = renderMarkdownToHtml('- a\n- b');
|
||||
expect(html).toContain('<ul class="md-ul">');
|
||||
expect(html).toContain('<li class="md-li">a</li>');
|
||||
expect(html).toContain('<li class="md-li">b</li>');
|
||||
});
|
||||
|
||||
it('一级标题渲染为 h2', () => {
|
||||
const { html } = renderMarkdownToHtml('# Title');
|
||||
expect(html).toContain('<h2 class="md-h2">Title</h2>');
|
||||
});
|
||||
|
||||
it('代码块内容不被行内加粗转换', () => {
|
||||
const { html } = renderMarkdownToHtml('```\n**not bold**\n```');
|
||||
expect(html).toContain('<pre class="md-code-block">');
|
||||
expect(html).not.toContain('<strong>not bold</strong>');
|
||||
});
|
||||
|
||||
it('行内代码被抽取保护', () => {
|
||||
const { html } = renderMarkdownToHtml('use `npm run` here');
|
||||
expect(html).toContain('<code class="md-inline-code">npm run</code>');
|
||||
});
|
||||
|
||||
it('[文本](url) 链接渲染', () => {
|
||||
const { html } = renderMarkdownToHtml('[Google](https://g.com)');
|
||||
expect(html).toContain('<a class="md-link" href="https://g.com"');
|
||||
expect(html).toContain('Google');
|
||||
});
|
||||
|
||||
it('媒体(<img>)以占位符保留并返回结构化 media 列表', () => {
|
||||
const { html, media } = renderMarkdownToHtml('看这张图 <img src="https://x.com/a.png" alt="图">');
|
||||
expect(media.length).toBe(1);
|
||||
expect(media[0].type).toBe('img');
|
||||
expect(media[0].src).toBe('https://x.com/a.png');
|
||||
expect(media[0].alt).toBe('图');
|
||||
expect(html).toContain('\x00MEDIA0\x00');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
import katex from 'katex';
|
||||
import hljs from 'highlight.js';
|
||||
|
||||
export interface MediaInfo {
|
||||
type: 'img' | 'video';
|
||||
src: string;
|
||||
alt?: string;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
html: string;
|
||||
media: MediaInfo[];
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Markdown 文本转为带占位符的 HTML 字符串。
|
||||
*
|
||||
* 设计契约(曾被线上 bug 击穿、用单测固化,见 markdown.test.ts):
|
||||
* - 段落内【单个 \n 转为空格】而非 <br/>,避免 AI 回复被强制大量换行;
|
||||
* - 【3+ 连续空行压缩为 2 个】(/\n{3,}/ -> \n\n),避免多余空白把内容撑成多行;
|
||||
* - 【表格在加粗/链接转换之后提取】,单元格内的 **xxx** / [文本](url) 才能被渲染;
|
||||
* 且单元格内连续 <br> 被压缩为单个(normalizeCell)。
|
||||
*
|
||||
* 媒体(<img>/<video>)以 \x00MEDIA<n>\x00 占位符保留在返回的 html 中,
|
||||
* 由调用方(ChatPage 的 MarkdownContent)切分后渲染为 React 组件。
|
||||
*/
|
||||
export function renderMarkdownToHtml(content: string): RenderResult {
|
||||
let text = content;
|
||||
|
||||
// 1. Extract code blocks first (protect from other replacements)
|
||||
const codeBlocks: string[] = [];
|
||||
const mermaidBlocks: string[] = [];
|
||||
text = text.replace(/```(\w*)\n?([\s\S]*?)```/g, (_m: string, _lang: string, code: string) => {
|
||||
if (_lang === 'mermaid') {
|
||||
const idx = mermaidBlocks.length;
|
||||
mermaidBlocks.push('<div class="md-mermaid" data-code="' + escapeHtml(code.trim()) + '"></div>');
|
||||
return '\x00MERMAID' + idx + '\x00';
|
||||
}
|
||||
const idx = codeBlocks.length;
|
||||
codeBlocks.push('<pre class="md-code-block"><code class="md-code">' + escapeHtml(code.trim()) + '</code></pre>');
|
||||
return '\x00CODEBLOCK' + idx + '\x00';
|
||||
});
|
||||
|
||||
// 2. Extract inline code
|
||||
const inlineCodes: string[] = [];
|
||||
text = text.replace(/`([^`]+)`/g, (_m: string, code: string) => {
|
||||
const idx = inlineCodes.length;
|
||||
inlineCodes.push('<code class="md-inline-code">' + escapeHtml(code) + '</code>');
|
||||
return '\x00INLINE' + idx + '\x00';
|
||||
});
|
||||
|
||||
// 2.5 Extract media blocks (<img>/<video>) -> 结构化,后续渲染为 React 组件
|
||||
const mediaBlocks: MediaInfo[] = [];
|
||||
text = text.replace(/<(img|video)([^>]*?)\/?>/gi, (_m: string, tag: string, attrs: string) => {
|
||||
const type = tag.toLowerCase() === 'img' ? 'img' : 'video';
|
||||
const srcM = attrs.match(/src=["']([^"']+)["']/i);
|
||||
const altM = attrs.match(/alt=["']([^"']*)["']/i);
|
||||
mediaBlocks.push({ type, src: srcM ? srcM[1] : '', alt: altM ? altM[1] : '' });
|
||||
return '\x00MEDIA' + (mediaBlocks.length - 1) + '\x00';
|
||||
});
|
||||
|
||||
// 2.6 Normalize excessive blank lines in prose (code blocks already extracted)
|
||||
text = text.replace(/\n{3,}/g, '\n\n').trim();
|
||||
|
||||
// 2.8 LaTeX 数学公式:$$...$$(块级)和 $...$(行内)
|
||||
const mathBlocks: string[] = [];
|
||||
text = text.replace(/\$\$([\s\S]+?)\$\$/g, (_m: string, formula: string) => {
|
||||
try {
|
||||
const rendered = katex.renderToString(formula.trim(), { displayMode: true, throwOnError: false });
|
||||
const idx = mathBlocks.length;
|
||||
mathBlocks.push(`<div class="md-math-block">${rendered}</div>`);
|
||||
return '\x00MATHBLOCK' + idx + '\x00';
|
||||
} catch { return _m; }
|
||||
});
|
||||
text = text.replace(/\$([^\s$][^$]*[^\s$])\$/g, (_m: string, formula: string) => {
|
||||
try {
|
||||
const rendered = katex.renderToString(formula.trim(), { displayMode: false, throwOnError: false });
|
||||
const idx = mathBlocks.length;
|
||||
mathBlocks.push(`<span class="md-math-inline">${rendered}</span>`);
|
||||
return '\x00MATHBLOCK' + idx + '\x00';
|
||||
} catch { return _m; }
|
||||
});
|
||||
|
||||
// 2.9 Strikethrough: ~~text~~ -> <del>text</del>
|
||||
text = text.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||||
|
||||
// 2.10 Auto-link bare URLs: http(s)://... -> <a>
|
||||
text = text.replace(/(?<![="'>])https?:\/\/[^\s<>[\]()]+/g, (url: string) =>
|
||||
`<a class="md-link" href="${url}" target="_blank" rel="noopener">${url}</a>`
|
||||
);
|
||||
|
||||
// 3. Headers
|
||||
text = text.replace(/^#### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||
text = text.replace(/^### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||
text = text.replace(/^## (.+)$/gm, '<h3 class="md-h3">$1</h3>');
|
||||
text = text.replace(/^# (.+)$/gm, '<h2 class="md-h2">$1</h2>');
|
||||
|
||||
// 4. Horizontal rule
|
||||
text = text.replace(/^---+$/gm, '<hr class="md-hr">');
|
||||
|
||||
// 5. Blockquotes
|
||||
text = text.replace(/^> (.+)$/gm, '<blockquote class="md-blockquote">$1</blockquote>');
|
||||
|
||||
// 6. Links [text](url)
|
||||
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a class="md-link" href="$2" target="_blank" rel="noopener">$1</a>');
|
||||
|
||||
// 7. Bold and italic
|
||||
text = text.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||
text = text.replace(/(?<!\w)\*(?!\*)(.+?)(?<!\*)\*(?!\w)/g, '<em>$1</em>');
|
||||
|
||||
// 7.5 Extract Markdown tables after inline formatting so cells support bold/italic/links.
|
||||
// 表格提取放在加粗/链接之后,避免单元格内 **xxx** 原样显示;同时压缩单元格内多余 <br>。
|
||||
const tableBlocks: string[] = [];
|
||||
text = text.replace(
|
||||
/((?:^\|.+\|\r?\n)+^\|[\s\-:|]+\|\r?\n(?:^\|.+\|\r?\n?)+)/gm,
|
||||
(_m: string, block: string) => {
|
||||
const lines = block.trim().split(/\r?\n/).filter((l: string) => l.trim());
|
||||
if (lines.length < 2) return block;
|
||||
const headerCells = lines[0].split('|').slice(1, -1).map((c: string) => c.trim());
|
||||
const alignCells = lines[1].split('|').slice(1, -1).map((c: string) => {
|
||||
const t = c.trim();
|
||||
const left = t.startsWith(':');
|
||||
const right = t.endsWith(':');
|
||||
if (left && right) return 'center';
|
||||
if (right) return 'right';
|
||||
if (left) return 'left';
|
||||
return 'left';
|
||||
});
|
||||
const normalizeCell = (cell: string) => {
|
||||
return cell
|
||||
.replace(/<br\s*\/?>\s*/gi, '<br/>')
|
||||
.replace(/\n/g, '<br/>')
|
||||
.replace(/(<br\/>){2,}/g, '<br/>')
|
||||
.replace(/^(<br\/>)+|(<br\/>)+$/g, '');
|
||||
};
|
||||
const bodyRows = lines.slice(2).map((row: string) =>
|
||||
row.split('|').slice(1, -1).map((c: string) => normalizeCell(c.trim()))
|
||||
);
|
||||
const thead = headerCells.map((c: string, i: number) =>
|
||||
`<th style="text-align:${alignCells[i] || 'left'}">${normalizeCell(c)}</th>`
|
||||
).join('');
|
||||
const tbody = bodyRows.map((r: string[]) =>
|
||||
'<tr>' + r.map((c: string, i: number) =>
|
||||
`<td style="text-align:${alignCells[i] || 'left'}">${c}</td>`
|
||||
).join('') + '</tr>'
|
||||
).join('');
|
||||
const html = `<table class="md-table"><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table>`;
|
||||
const idx = tableBlocks.length;
|
||||
tableBlocks.push(html);
|
||||
return '\x00TABLE' + idx + '\x00';
|
||||
}
|
||||
);
|
||||
|
||||
// 8. Lists
|
||||
text = text.replace(/^\s*[-*] (.+)$/gm, '<li class="md-li">$1</li>');
|
||||
text = text.replace(/^\s*\d+\. (.+)$/gm, '<li class="md-li">$1</li>');
|
||||
// Wrap consecutive <li> in <ul>
|
||||
text = text.replace(/((?:<li class="md-li">[\s\S]*?<\/li>\n?)+)/g, '<ul class="md-ul">$1</ul>');
|
||||
|
||||
// 9. Convert double newlines to paragraph breaks, single newlines to spaces
|
||||
text = text.replace(/\n\n/g, '</p><p class="md-p">');
|
||||
text = text.replace(/\n/g, ' ');
|
||||
|
||||
// 10. Restore code blocks and inline codes
|
||||
text = text.replace(/\x00CODEBLOCK(\d+)\x00/g, (_m: string, idx: string) => codeBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00MERMAID(\d+)\x00/g, (_m: string, idx: string) => mermaidBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00INLINE(\d+)\x00/g, (_m: string, idx: string) => inlineCodes[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00TABLE(\d+)\x00/g, (_m: string, idx: string) => tableBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00MATHBLOCK(\d+)\x00/g, (_m: string, idx: string) => mathBlocks[parseInt(idx)] || '');
|
||||
|
||||
// 10.5 Apply syntax highlighting to code blocks + add copy button
|
||||
text = text.replace(
|
||||
/<pre class="md-code-block"><code class="md-code">([\s\S]*?)<\/code><\/pre>/g,
|
||||
(_m: string, code: string) => {
|
||||
const decoded = code.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
let highlighted: string;
|
||||
try { highlighted = hljs.highlightAuto(decoded).value; } catch { highlighted = code; }
|
||||
return `<div class="md-code-wrapper">
|
||||
<button class="md-code-copy" onclick="navigator.clipboard.writeText(this.parentElement.querySelector('code').textContent);this.textContent='已复制';setTimeout(()=>this.textContent='复制',2000)">复制</button>
|
||||
<pre class="md-code-block"><code class="md-code hljs">${highlighted}</code></pre>
|
||||
</div>`;
|
||||
}
|
||||
);
|
||||
|
||||
// 11. Wrap in paragraph and clean up
|
||||
text = '<p class="md-p">' + text + '</p>';
|
||||
text = text.replace(/<p class="md-p"><\/p>/g, '');
|
||||
text = text.replace(/<p class="md-p">(<h[234][\s\S]*?<\/h[234]>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<pre[\s\S]*?<\/pre>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<ul[\s\S]*?<\/ul>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<hr[\s\S]*?)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<blockquote[\s\S]*?<\/blockquote>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<table[\s\S]*?<\/table>)<\/p>/g, '$1');
|
||||
|
||||
return { html: text, media: mediaBlocks };
|
||||
}
|
||||
@@ -70,7 +70,7 @@ CREATE TABLE IF NOT EXISTS `skill_trajectory_links` (
|
||||
`skill_name` VARCHAR(200) NOT NULL,
|
||||
`user_id` VARCHAR(36) NOT NULL,
|
||||
`trajectory_id` VARCHAR(36),
|
||||
`atom_id` VARCHAR(36),
|
||||
`atom_id` VARCHAR(128),
|
||||
`weightscore` INT DEFAULT 0,
|
||||
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX `idx_stl_user_skill` (`user_id`, `skill_name`),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- 021: 加宽 skill_trajectory_links.atom_id 列
|
||||
-- 背景:atom_id 实际值形如 "{trajectory_id}_atom_{i}"(UUID 36 + "_atom_" + 序号 ≈ 45 字符),
|
||||
-- 原 VARCHAR(36) 过短导致写入时 DataError(1406) Data too long,并使会话进入 rolled-back 状态,
|
||||
-- 级联触发 PendingRollbackError 与日志 trace_id KeyError 刷屏。
|
||||
-- 本迁移幂等:重复执行 MODIFY 到相同类型为无害 no-op。
|
||||
|
||||
ALTER TABLE `skill_trajectory_links` MODIFY COLUMN `atom_id` VARCHAR(128) NULL;
|
||||
@@ -56,7 +56,7 @@ CREATE TABLE IF NOT EXISTS `distribution_licenses` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Insert seed data: sample distributions
|
||||
INSERT INTO `distributions` (`id`, `name`, `description`, `brand_name`, `brand_color`, `provider`, `model`, `features`, `status`) VALUES
|
||||
INSERT IGNORE INTO `distributions` (`id`, `name`, `description`, `brand_name`, `brand_color`, `provider`, `model`, `features`, `status`) VALUES
|
||||
('distro-starter', 'Starter Edition', '基础版发行包,适合个人开发者和小团队', 'AI Starter', '#6366f1', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec"]', 'active'),
|
||||
('distro-enterprise', 'Enterprise Edition', '企业版发行包,包含完整 MCP 生态 + Agent 协作', 'AI Enterprise', '#f59e0b', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "knowledge_search", "agent_collab"]', 'active'),
|
||||
('distro-devops', 'DevOps Edition', 'DevOps 专用发行包,CI/CD + 代码审查 + 部署', 'AI DevOps', '#10b981', 'siliconflow', 'deepseek-ai/DeepSeek-V4-Flash', '["chat", "code_exec", "automation", "webhook"]', 'active');
|
||||
@@ -84,6 +84,11 @@ CREATE TABLE IF NOT EXISTS usage_reports (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 5. Add privacy_mode to distributions table
|
||||
ALTER TABLE distributions
|
||||
ADD COLUMN IF NOT EXISTS privacy_mode ENUM('local', 'cloud', 'hybrid') NOT NULL DEFAULT 'cloud'
|
||||
COMMENT 'Deployment mode for distribution' AFTER status;
|
||||
-- MariaDB 11.8 不支持 ADD COLUMN IF NOT EXISTS 语法,改用 information_schema 预检 + 动态 PREPARE 实现幂等
|
||||
SET @exist_pm := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'aiflow' AND TABLE_NAME = 'distributions' AND COLUMN_NAME = 'privacy_mode');
|
||||
SET @sql_pm := IF(@exist_pm = 0,
|
||||
"ALTER TABLE distributions ADD COLUMN privacy_mode ENUM('local', 'cloud', 'hybrid') NOT NULL DEFAULT 'cloud' COMMENT 'Deployment mode for distribution' AFTER status",
|
||||
'SELECT 1');
|
||||
PREPARE stmt_pm FROM @sql_pm;
|
||||
EXECUTE stmt_pm;
|
||||
DEALLOCATE PREPARE stmt_pm;
|
||||
Reference in new issue
Block a user