From c56aa6e7522e0ded83bf8d45523b7da302ad3011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=AD=90=E9=BB=98?= <925456043@qq.com> Date: Sat, 29 Aug 2026 13:32:57 +0800 Subject: [PATCH] init --- .gitignore | 19 + README.md | 33 + compose.yml | 25 + sandbox/.dockerignore | 2 + sandbox/Dockerfile | 41 + sandbox/document_view.py | 309 ++ sandbox/fonts-local.conf | 20 + sandbox/package-lock.json | 974 +++++ sandbox/package.json | 15 + server/pom.xml | 110 + .../smartfactory/SmartFactoryApplication.java | 24 + .../smartfactory/agent/AgentController.java | 141 + .../smartfactory/agent/AgentEventService.java | 192 + .../agent/AgentExecutionService.java | 263 ++ .../smartfactory/agent/AgentFactory.java | 320 ++ .../agent/AgentOutputService.java | 179 + .../smartfactory/agent/AgentRunService.java | 684 ++++ .../smartfactory/agent/AgentRunStore.java | 233 ++ .../smartfactory/agent/DocumentViewTool.java | 169 + .../smartfactory/agent/PagedReadFileTool.java | 191 + .../agent/RunRecoveryService.java | 44 + .../artifact/ArtifactController.java | 59 + .../artifact/ArtifactService.java | 307 ++ .../smartfactory/artifact/DocxValidator.java | 194 + .../smartfactory/auth/AuthController.java | 104 + .../smartfactory/auth/UserService.java | 97 + .../smartfactory/common/ApiError.java | 15 + .../smartfactory/common/ApiException.java | 44 + .../common/GlobalExceptionHandler.java | 135 + .../smartfactory/common/TraceIdFilter.java | 45 + .../smartfactory/config/AppProperties.java | 37 + .../smartfactory/config/InfraConfig.java | 36 + .../smartfactory/config/SecurityConfig.java | 96 + .../config/SkillRepositoryConfig.java | 31 + .../smartfactory/model/KeyCipher.java | 84 + .../smartfactory/model/ModelController.java | 96 + .../smartfactory/model/ModelService.java | 452 +++ .../project/ProjectController.java | 213 + .../project/ProjectFileService.java | 438 ++ .../smartfactory/project/ProjectService.java | 326 ++ .../smartfactory/skill/SkillController.java | 113 + .../skill/SkillPackageReader.java | 149 + .../smartfactory/skill/SkillService.java | 368 ++ server/src/main/resources/application.yml | 49 + .../db/migration/V1__initial_schema.sql | 246 ++ .../prompts/smart-factory-agent-system.md | 39 + .../prompts/smart-factory-compaction.md | 9 + .../DatabaseAndEventIntegrationTest.java | 238 ++ .../smartfactory/KeyCipherAndShellTest.java | 35 + .../agent/AgentExecutionServiceTest.java | 27 + .../agent/AgentRunServiceTest.java | 81 + .../agent/DocumentViewToolTest.java | 28 + .../agent/PagedReadFileToolTest.java | 66 + .../artifact/DocxValidatorTest.java | 125 + .../smartfactory/auth/AuthControllerTest.java | 43 + .../common/GlobalExceptionHandlerTest.java | 24 + .../project/ProjectFileServiceTest.java | 87 + .../smartfactory/skill/SkillArchiveTest.java | 73 + web-ui/index.html | 13 + web-ui/package-lock.json | 3608 +++++++++++++++++ web-ui/package.json | 29 + web-ui/src/App.vue | 106 + web-ui/src/api.ts | 142 + web-ui/src/components/AgentTimeline.test.ts | 131 + web-ui/src/components/AgentTimeline.vue | 371 ++ web-ui/src/components/MaterialAskCard.vue | 112 + web-ui/src/components/PlanCard.vue | 91 + web-ui/src/eventCache.ts | 57 + web-ui/src/eventUtils.test.ts | 19 + web-ui/src/eventUtils.ts | 10 + web-ui/src/main.ts | 32 + web-ui/src/pages/LoginPage.vue | 45 + web-ui/src/pages/ModelsPage.vue | 124 + web-ui/src/pages/ProjectPage.vue | 426 ++ web-ui/src/pages/SkillsPage.vue | 89 + web-ui/src/router.ts | 13 + web-ui/src/styles.css | 247 ++ web-ui/tsconfig.app.json | 18 + web-ui/tsconfig.json | 7 + web-ui/tsconfig.node.json | 11 + web-ui/vite.config.ts | 21 + 81 files changed, 14319 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 compose.yml create mode 100644 sandbox/.dockerignore create mode 100644 sandbox/Dockerfile create mode 100644 sandbox/document_view.py create mode 100644 sandbox/fonts-local.conf create mode 100644 sandbox/package-lock.json create mode 100644 sandbox/package.json create mode 100644 server/pom.xml create mode 100644 server/src/main/java/cn/alphaline/smartfactory/SmartFactoryApplication.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentEventService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentExecutionService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentFactory.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentOutputService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunStore.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/DocumentViewTool.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/PagedReadFileTool.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/agent/RunRecoveryService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/artifact/DocxValidator.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/auth/AuthController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/auth/UserService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/common/ApiError.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/common/ApiException.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/common/GlobalExceptionHandler.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/common/TraceIdFilter.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/config/AppProperties.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/config/InfraConfig.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/config/SecurityConfig.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/config/SkillRepositoryConfig.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/model/KeyCipher.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/model/ModelController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/model/ModelService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/project/ProjectController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/project/ProjectFileService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/project/ProjectService.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/skill/SkillController.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/skill/SkillPackageReader.java create mode 100644 server/src/main/java/cn/alphaline/smartfactory/skill/SkillService.java create mode 100644 server/src/main/resources/application.yml create mode 100644 server/src/main/resources/db/migration/V1__initial_schema.sql create mode 100644 server/src/main/resources/prompts/smart-factory-agent-system.md create mode 100644 server/src/main/resources/prompts/smart-factory-compaction.md create mode 100644 server/src/test/java/cn/alphaline/smartfactory/DatabaseAndEventIntegrationTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/KeyCipherAndShellTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/agent/AgentExecutionServiceTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/agent/AgentRunServiceTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/agent/DocumentViewToolTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/agent/PagedReadFileToolTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/artifact/DocxValidatorTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/auth/AuthControllerTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/common/GlobalExceptionHandlerTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/project/ProjectFileServiceTest.java create mode 100644 server/src/test/java/cn/alphaline/smartfactory/skill/SkillArchiveTest.java create mode 100644 web-ui/index.html create mode 100644 web-ui/package-lock.json create mode 100644 web-ui/package.json create mode 100644 web-ui/src/App.vue create mode 100644 web-ui/src/api.ts create mode 100644 web-ui/src/components/AgentTimeline.test.ts create mode 100644 web-ui/src/components/AgentTimeline.vue create mode 100644 web-ui/src/components/MaterialAskCard.vue create mode 100644 web-ui/src/components/PlanCard.vue create mode 100644 web-ui/src/eventCache.ts create mode 100644 web-ui/src/eventUtils.test.ts create mode 100644 web-ui/src/eventUtils.ts create mode 100644 web-ui/src/main.ts create mode 100644 web-ui/src/pages/LoginPage.vue create mode 100644 web-ui/src/pages/ModelsPage.vue create mode 100644 web-ui/src/pages/ProjectPage.vue create mode 100644 web-ui/src/pages/SkillsPage.vue create mode 100644 web-ui/src/router.ts create mode 100644 web-ui/src/styles.css create mode 100644 web-ui/tsconfig.app.json create mode 100644 web-ui/tsconfig.json create mode 100644 web-ui/tsconfig.node.json create mode 100644 web-ui/vite.config.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ad5eca --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +server/target/ +web-ui/node_modules/ +web-ui/dist/ +sandbox/node_modules/ +*.tsbuildinfo +data/ +.idea/ +*.iml +*.log +.env +.env.local +.DS_Store +dashscope_key.txt +deepseek_key.txt +__pycache__/ +*.py[cod] +.env.* +!.env.example +test_data/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d96e2e4 --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# 智造申报 Agent + +面向智能工厂申报的 Harness Agent 应用。用户创建企业项目并上传可用材料;Agent 完成材料检验与建设规划确认后,自主调用知识库、Skill 和受控工作区生成带 Word 原生批注的 DOCX 审阅稿。 + +## 技术栈 + +- Spring Boot 3.5.16、JDK 21、AgentScope Java 2.0.1、AG-UI +- Vue 3.5、Vite、Element Plus、Vue Element Plus X +- PostgreSQL 17、Flyway + +## 本地启动 + +```bash +docker compose --profile build-only build agent-runtime +docker compose up -d postgres +mvn -q -f server/pom.xml spring-boot:run +npm --prefix client install +npm --prefix client run dev +``` + +打开 ,本地默认账号为 `admin / admin123`。 + +项目根目录的 `deepseek_key.txt` 和 `dashscope_key.txt` 分别供模型与百炼知识库使用;模型、Skill 也可在页面内查看或配置。 + +## 验证 + +```bash +mvn -q -f server/pom.xml test +npm --prefix client run test -- --run +npm --prefix client run build +``` + +产品、数据库与验收设计见 [docs](docs/)。标准 Skill 源文件位于 [标准Skills](标准Skills/),仅作为开发素材保留,不参与应用启动同步。 diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..dfe0b74 --- /dev/null +++ b/compose.yml @@ -0,0 +1,25 @@ +services: + agent-runtime: + image: smart-factory-agent-runtime:0.1.0 + build: + context: sandbox + profiles: ["build-only"] + + postgres: + image: postgres:17-alpine + environment: + POSTGRES_DB: smart_factory_agent + POSTGRES_USER: smart_factory + POSTGRES_PASSWORD: smart_factory + ports: + - "127.0.0.1:54330:5432" + volumes: + - smart-factory-pg:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U smart_factory -d smart_factory_agent"] + interval: 3s + timeout: 3s + retries: 20 + +volumes: + smart-factory-pg: diff --git a/sandbox/.dockerignore b/sandbox/.dockerignore new file mode 100644 index 0000000..93f1361 --- /dev/null +++ b/sandbox/.dockerignore @@ -0,0 +1,2 @@ +node_modules +npm-debug.log diff --git a/sandbox/Dockerfile b/sandbox/Dockerfile new file mode 100644 index 0000000..9f818a4 --- /dev/null +++ b/sandbox/Dockerfile @@ -0,0 +1,41 @@ +FROM node:22-bookworm-slim AS node +FROM eclipse-temurin:21-jre-jammy AS java +FROM python:3.12-slim-bookworm + +COPY --from=node /usr/local /usr/local + +ENV JAVA_HOME=/opt/java/openjdk \ + PATH=/opt/java/openjdk/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin \ + NODE_PATH=/opt/agent-runtime/node_modules \ + PLAYWRIGHT_BROWSERS_PATH=/opt/agent-runtime/ms-playwright \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /opt/agent-runtime +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev \ + && pip install --no-cache-dir \ + defusedxml lxml "markitdown[pptx]" openpyxl pandas xlrd python-pptx pillow six \ + pypdf pdfplumber reportlab pdf2image pytesseract pypdfium2 + +COPY --from=java /opt/java/openjdk /opt/java/openjdk +RUN ln -s /opt/java/openjdk/bin/java /usr/local/bin/java \ + && apt-get update \ + && apt-get install -y --no-install-recommends \ + adduser ca-certificates file findutils fonts-noto-cjk gawk git grep \ + libreoffice-calc libreoffice-impress libreoffice-writer \ + pandoc poppler-utils qpdf ripgrep sed tesseract-ocr tesseract-ocr-chi-sim unzip zip \ + && npx playwright install --with-deps chromium \ + && /usr/sbin/adduser --disabled-password --gecos "" --uid 10001 agent \ + && mkdir -p /workspace \ + && chown agent:agent /workspace \ + && rm -rf /var/lib/apt/lists/* + +COPY fonts-local.conf /etc/fonts/local.conf +RUN fc-cache -f + +COPY --chown=agent:agent document_view.py ./ +USER agent +WORKDIR /workspace + +CMD ["sleep", "infinity"] diff --git a/sandbox/document_view.py b/sandbox/document_view.py new file mode 100644 index 0000000..02b1432 --- /dev/null +++ b/sandbox/document_view.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Render selected document pages, slides, sheets, ranges, or images for multimodal review.""" + +from __future__ import annotations + +import json +import math +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont, ImageOps + +WORKSPACE = Path("/workspace").resolve() +ALLOWED_ROOTS = tuple((WORKSPACE / name).resolve() for name in ("inputs", "work", "references", "artifacts")) +MAX_PIXELS = 8_000_000 +MAX_IMAGE_BYTES = 4 * 1024 * 1024 +MAX_TOTAL_BYTES = 20 * 1024 * 1024 +MAX_CELLS = 2_400 +COMMAND_TIMEOUT_SECONDS = 45 +TOTAL_TIMEOUT_SECONDS = 170 + + +def safe_source(value: str) -> Path: + """Resolve a workspace-relative source and reject traversal or unsupported roots.""" + path = (WORKSPACE / value).resolve() + if not any(path == root or path.is_relative_to(root) for root in ALLOWED_ROOTS): + raise ValueError("文档路径必须位于 inputs、work、references 或 artifacts") + if not path.is_file(): + raise ValueError("文档不存在") + return path + + +def run(command: list[str]) -> None: + """Run a renderer command with bounded execution time and useful errors.""" + result = subprocess.run(command, capture_output=True, text=True, timeout=COMMAND_TIMEOUT_SECONDS, check=False) + if result.returncode: + detail = (result.stderr or result.stdout or "渲染命令失败").strip() + raise RuntimeError(detail[-600:]) + + +def office_pdf(source: Path, directory: Path) -> Path: + """Convert an Office document to PDF with an isolated LibreOffice profile.""" + profile = directory / "lo-profile" + run([ + "libreoffice", "--headless", f"-env:UserInstallation=file://{profile}", + "--convert-to", "pdf", "--outdir", str(directory), str(source), + ]) + target = directory / f"{source.stem}.pdf" + if not target.is_file(): + raise RuntimeError("LibreOffice 未生成 PDF") + return target + + +def render_pdf(source: Path, page: int, dpi: int, target: Path, fmt: str) -> None: + """Render one one-based PDF page.""" + output_type = "jpeg" if fmt == "jpeg" else "png" + stem = target.with_suffix("") + run([ + "pdftoppm", "-f", str(page), "-l", str(page), "-singlefile", "-r", str(dpi), + f"-{output_type}", str(source), str(stem), + ]) + produced = stem.with_suffix(".jpg" if output_type == "jpeg" else ".png") + if not produced.is_file(): + raise RuntimeError("未找到指定页,请检查页码") + produced.replace(target.with_suffix(produced.suffix)) + + +def font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: + """Load a CJK font available in the runtime image.""" + names = [ + "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + ] + for name in names: + if Path(name).is_file(): + return ImageFont.truetype(name, size) + return ImageFont.load_default() + + +def cell_text(value: object) -> str: + """Format a spreadsheet cell for visual review.""" + if value is None: + return "" + text = str(value).replace("\r", " ").replace("\n", " ") + return text if len(text) <= 80 else f"{text[:79]}…" + + +def draw_grid(values: list[list[object]], target: Path, title: str) -> None: + """Render a bounded spreadsheet range as a readable table image.""" + rows = len(values) + columns = max((len(row) for row in values), default=0) + if rows == 0 or columns == 0: + raise ValueError("所选工作表范围为空") + if rows * columns > MAX_CELLS: + raise ValueError(f"所选范围包含 {rows * columns} 个单元格,请拆分为多个较小范围") + + body_font = font(18) + title_font = font(20, True) + widths = [] + for column in range(columns): + longest = max((len(cell_text(row[column])) if column < len(row) else 0 for row in values), default=0) + widths.append(min(240, max(72, 18 + longest * 11))) + row_height = 38 + title_height = 48 + width = sum(widths) + 2 + height = title_height + rows * row_height + 2 + scale = min(1.0, math.sqrt(MAX_PIXELS / max(1, width * height))) + if scale < 1: + widths = [max(42, int(value * scale)) for value in widths] + row_height = max(24, int(row_height * scale)) + title_height = max(34, int(title_height * scale)) + body_font = font(max(12, int(18 * scale))) + title_font = font(max(14, int(20 * scale)), True) + width = sum(widths) + 2 + height = title_height + rows * row_height + 2 + + image = Image.new("RGB", (width, height), "white") + painter = ImageDraw.Draw(image) + painter.rectangle((0, 0, width - 1, title_height), fill="#f1f5f9") + painter.text((12, 11), title, fill="#334155", font=title_font) + y = title_height + for row_index, row in enumerate(values): + x = 1 + fill = "#f8fafc" if row_index % 2 else "#ffffff" + for column, cell_width in enumerate(widths): + painter.rectangle((x, y, x + cell_width, y + row_height), fill=fill, outline="#dbe3ed") + painter.text((x + 7, y + 8), cell_text(row[column] if column < len(row) else None), + fill="#253247", font=body_font) + x += cell_width + y += row_height + image.save(target, "PNG", optimize=True) + + +def render_sheet(source: Path, sheet: str | None, selected_range: str | None, target: Path) -> str: + """Render a selected spreadsheet range and return the actual sheet/range label.""" + if source.suffix.lower() == ".xls": + import pandas as pd + book = pd.ExcelFile(source) + sheet_name = sheet or book.sheet_names[0] + frame = pd.read_excel(source, sheet_name=sheet_name, header=None) + from openpyxl.utils.cell import range_boundaries + if selected_range: + min_col, min_row, max_col, max_row = range_boundaries(selected_range) + frame = frame.iloc[min_row - 1:max_row, min_col - 1:max_col] + else: + frame = frame.iloc[:60, :20] + selected_range = f"A1:{_column_name(max(1, frame.shape[1]))}{max(1, frame.shape[0])}" + values = frame.where(frame.notna(), None).values.tolist() + else: + from openpyxl import load_workbook + from openpyxl.utils.cell import range_boundaries + book = load_workbook(source, read_only=True, data_only=False) + sheet_name = sheet or book.sheetnames[0] + if sheet_name not in book.sheetnames: + raise ValueError(f"工作表不存在:{sheet_name}") + worksheet = book[sheet_name] + if selected_range: + min_col, min_row, max_col, max_row = range_boundaries(selected_range) + else: + min_col, min_row = 1, 1 + max_col, max_row = min(20, worksheet.max_column), min(60, worksheet.max_row) + selected_range = f"A1:{_column_name(max_col)}{max_row}" + values = [ + list(row) + for row in worksheet.iter_rows( + min_row=min_row, + max_row=max_row, + min_col=min_col, + max_col=max_col, + values_only=True, + ) + ] + book.close() + label = f"{sheet_name}!{selected_range}" + draw_grid(values, target, label) + return label + + +def _column_name(index: int) -> str: + """Convert a one-based column index to an Excel column name.""" + value = "" + while index: + index, remainder = divmod(index - 1, 26) + value = chr(65 + remainder) + value + return value + + +def normalize_image(path: Path, target: Path) -> None: + """Normalize an uploaded image and bound its dimensions.""" + with Image.open(path) as source: + image = ImageOps.exif_transpose(source).convert("RGB") + if image.width * image.height > MAX_PIXELS: + scale = math.sqrt(MAX_PIXELS / (image.width * image.height)) + image = image.resize((max(1, int(image.width * scale)), max(1, int(image.height * scale)))) + image.save(target, "JPEG", quality=88, optimize=True) + + +def bound_image(path: Path) -> Path: + """Bound image pixels and bytes, converting oversized PNG files to JPEG.""" + with Image.open(path) as source: + width, height = source.size + if width * height > MAX_PIXELS: + scale = math.sqrt(MAX_PIXELS / (width * height)) + image = source.convert("RGB").resize((max(1, int(width * scale)), max(1, int(height * scale)))) + replacement = path.with_suffix(".jpg") + image.save(replacement, "JPEG", quality=88, optimize=True) + path.unlink(missing_ok=True) + path = replacement + if path.stat().st_size > MAX_IMAGE_BYTES and path.suffix.lower() != ".jpg": + with Image.open(path) as source: + replacement = path.with_suffix(".jpg") + source.convert("RGB").save(replacement, "JPEG", quality=84, optimize=True) + path.unlink(missing_ok=True) + path = replacement + if path.stat().st_size > MAX_IMAGE_BYTES: + raise ValueError("渲染图片过大,请降低 DPI 或缩小工作表范围") + return path + + +def render(view: dict, index: int, output: Path) -> dict: + """Render one requested view and return persisted metadata.""" + source = safe_source(str(view.get("path", ""))) + page = max(1, int(view.get("page") or 1)) + dpi = min(220, max(72, int(view.get("dpi") or 144))) + fmt = "jpeg" if str(view.get("format", "png")).lower() in {"jpg", "jpeg"} else "png" + suffix = source.suffix.lower() + target = output / f"render-{index}.{'jpg' if fmt == 'jpeg' else 'png'}" + label = f"第 {page} 页" + + if suffix == ".pdf": + render_pdf(source, page, dpi, target, fmt) + elif suffix in {".pptx", ".docx"}: + with tempfile.TemporaryDirectory(dir=output) as temporary: + converted = office_pdf(source, Path(temporary)) + render_pdf(converted, page, dpi, target, fmt) + label = f"第 {page} 张" if suffix == ".pptx" else f"第 {page} 页" + elif suffix in {".xls", ".xlsx"}: + target = target.with_suffix(".png") + label = render_sheet(source, view.get("sheet"), view.get("range"), target) + elif suffix in {".png", ".jpg", ".jpeg", ".webp"}: + target = target.with_suffix(".jpg") + normalize_image(source, target) + label = "原图" + else: + raise ValueError(f"document_view 暂不支持 {suffix or '无扩展名'} 文件") + + target = bound_image(target) + with Image.open(target) as image: + width, height = image.size + return { + "index": index, + "sourcePath": str(source.relative_to(WORKSPACE)), + "path": str(target.relative_to(WORKSPACE)), + "label": label, + "mediaType": "image/jpeg" if target.suffix.lower() == ".jpg" else "image/png", + "width": width, + "height": height, + "sizeBytes": target.stat().st_size, + } + + +def main(request_path: Path, result_path: Path) -> int: + """Process all requested views and persist partial successes plus errors.""" + request_path = request_path.resolve() + result_path = result_path.resolve() + request = json.loads(request_path.read_text(encoding="utf-8")) + views = request.get("views") + if not isinstance(views, list) or not views: + raise ValueError("views 至少包含一个查看请求") + output = result_path.parent + output.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + images: list[dict] = [] + errors: list[dict] = [] + total_bytes = 0 + for index, view in enumerate(views, 1): + if time.monotonic() - started > TOTAL_TIMEOUT_SECONDS: + errors.append({"index": index, "error": "本次渲染已达到时间上限,请减少页面后重试"}) + continue + try: + image = render(view, index, output) + total_bytes += image["sizeBytes"] + if total_bytes > MAX_TOTAL_BYTES: + Path(WORKSPACE / image["path"]).unlink(missing_ok=True) + total_bytes -= image["sizeBytes"] + raise ValueError("本次渲染图片总量过大,请拆分调用") + images.append(image) + except Exception as exception: # Each failed view is returned to the Agent as an observation. + errors.append({"index": index, "path": str(view.get("path", "")), "error": str(exception)[:800]}) + result_path.write_text(json.dumps({"images": images, "errors": errors}, ensure_ascii=False), encoding="utf-8") + return 0 if images else 2 + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print("usage: document_view.py request.json result.json", file=sys.stderr) + raise SystemExit(2) + try: + raise SystemExit(main(Path(sys.argv[1]), Path(sys.argv[2]))) + except Exception as failure: + Path(sys.argv[2]).write_text( + json.dumps({"images": [], "errors": [{"index": 0, "error": str(failure)[:800]}]}, ensure_ascii=False), + encoding="utf-8", + ) + raise SystemExit(2) diff --git a/sandbox/fonts-local.conf b/sandbox/fonts-local.conf new file mode 100644 index 0000000..7efdebc --- /dev/null +++ b/sandbox/fonts-local.conf @@ -0,0 +1,20 @@ + + + + + SimSun + Noto Serif CJK SC + + + 宋体 + Noto Serif CJK SC + + + SimHei + Noto Sans CJK SC + + + 黑体 + Noto Sans CJK SC + + diff --git a/sandbox/package-lock.json b/sandbox/package-lock.json new file mode 100644 index 0000000..d8586cc --- /dev/null +++ b/sandbox/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "smart-factory-agent-runtime", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "smart-factory-agent-runtime", + "version": "0.1.0", + "dependencies": { + "docx": "^9.5.1", + "pdf-lib": "^1.17.1", + "playwright": "^1.62.1", + "pptxgenjs": "^4.0.1", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "react-icons": "^5.7.0", + "sharp": "^0.35.4" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime/node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.4.tgz", + "integrity": "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.4.tgz", + "integrity": "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz", + "integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.3.tgz", + "integrity": "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.3.tgz", + "integrity": "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.3.tgz", + "integrity": "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.3.tgz", + "integrity": "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.3.tgz", + "integrity": "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.3.tgz", + "integrity": "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.3.tgz", + "integrity": "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.3.tgz", + "integrity": "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.3.tgz", + "integrity": "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.3.tgz", + "integrity": "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.4.tgz", + "integrity": "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.4.tgz", + "integrity": "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.4.tgz", + "integrity": "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.4.tgz", + "integrity": "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.4.tgz", + "integrity": "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.4.tgz", + "integrity": "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.4.tgz", + "integrity": "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.4.tgz", + "integrity": "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz", + "integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.4.tgz", + "integrity": "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.4.tgz", + "integrity": "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.4.tgz", + "integrity": "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.4.tgz", + "integrity": "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@pdf-lib/standard-fonts": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz", + "integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==", + "license": "MIT", + "dependencies": { + "pako": "^1.0.6" + } + }, + "node_modules/@pdf-lib/upng": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz", + "integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==", + "license": "MIT", + "dependencies": { + "pako": "^1.0.10" + } + }, + "node_modules/@types/node": { + "version": "25.9.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.5.tgz", + "integrity": "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==", + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/docx": { + "version": "9.7.1", + "resolved": "https://registry.npmjs.org/docx/-/docx-9.7.1.tgz", + "integrity": "sha512-ilXFf9Moz47ABjFpDiA5s1w9lpb4EFSp7+5iiJSbfyYDM+bpZdAgLlSr7fW4aXhVe/E+F6QCv0EvRVFEd5CsWg==", + "license": "MIT", + "dependencies": { + "@types/node": "^25.2.3", + "hash.js": "^1.1.7", + "jszip": "^3.10.1", + "nanoid": "^5.1.3", + "xml": "^1.0.1", + "xml-js": "^1.6.8" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "node_modules/https": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz", + "integrity": "sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg==", + "license": "ISC" + }, + "node_modules/image-size": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz", + "integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==", + "license": "MIT", + "dependencies": { + "queue": "6.0.2" + }, + "bin": { + "image-size": "bin/image-size.js" + }, + "engines": { + "node": ">=16.x" + } + }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, + "node_modules/nanoid": { + "version": "5.1.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz", + "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/pdf-lib": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz", + "integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==", + "license": "MIT", + "dependencies": { + "@pdf-lib/standard-fonts": "^1.0.0", + "@pdf-lib/upng": "^1.0.1", + "pako": "^1.0.11", + "tslib": "^1.11.1" + } + }, + "node_modules/playwright": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.62.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/pptxgenjs": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pptxgenjs/-/pptxgenjs-4.0.1.tgz", + "integrity": "sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A==", + "license": "MIT", + "dependencies": { + "@types/node": "^22.8.1", + "https": "^1.0.0", + "image-size": "^1.2.1", + "jszip": "^3.10.1" + } + }, + "node_modules/pptxgenjs/node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/pptxgenjs/node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/queue": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/queue/-/queue-6.0.2.tgz", + "integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==", + "license": "MIT", + "dependencies": { + "inherits": "~2.0.3" + } + }, + "node_modules/react": { + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", + "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz", + "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.8" + } + }, + "node_modules/react-icons": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.7.0.tgz", + "integrity": "sha512-LBLy340Rzqy6+/yVhZKT3B/QpP1BZaesGqasf09HPOBzRarcDIFH0WwXlXQfE7q7ipxK4MSiC5DIBWURCny6fw==", + "license": "MIT", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, + "node_modules/sharp": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz", + "integrity": "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.4", + "@img/sharp-darwin-x64": "0.35.4", + "@img/sharp-freebsd-wasm32": "0.35.4", + "@img/sharp-libvips-darwin-arm64": "1.3.3", + "@img/sharp-libvips-darwin-x64": "1.3.3", + "@img/sharp-libvips-linux-arm": "1.3.3", + "@img/sharp-libvips-linux-arm64": "1.3.3", + "@img/sharp-libvips-linux-ppc64": "1.3.3", + "@img/sharp-libvips-linux-riscv64": "1.3.3", + "@img/sharp-libvips-linux-s390x": "1.3.3", + "@img/sharp-libvips-linux-x64": "1.3.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", + "@img/sharp-libvips-linuxmusl-x64": "1.3.3", + "@img/sharp-linux-arm": "0.35.4", + "@img/sharp-linux-arm64": "0.35.4", + "@img/sharp-linux-ppc64": "0.35.4", + "@img/sharp-linux-riscv64": "0.35.4", + "@img/sharp-linux-s390x": "0.35.4", + "@img/sharp-linux-x64": "0.35.4", + "@img/sharp-linuxmusl-arm64": "0.35.4", + "@img/sharp-linuxmusl-x64": "0.35.4", + "@img/sharp-webcontainers-wasm32": "0.35.4", + "@img/sharp-win32-arm64": "0.35.4", + "@img/sharp-win32-ia32": "0.35.4", + "@img/sharp-win32-x64": "0.35.4" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/xml": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz", + "integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==", + "license": "MIT" + }, + "node_modules/xml-js": { + "version": "1.6.11", + "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", + "integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==", + "license": "MIT", + "dependencies": { + "sax": "^1.2.4" + }, + "bin": { + "xml-js": "bin/cli.js" + } + } + } +} diff --git a/sandbox/package.json b/sandbox/package.json new file mode 100644 index 0000000..03b9b39 --- /dev/null +++ b/sandbox/package.json @@ -0,0 +1,15 @@ +{ + "name": "smart-factory-agent-runtime", + "private": true, + "version": "0.1.0", + "dependencies": { + "docx": "^9.5.1", + "pdf-lib": "^1.17.1", + "playwright": "^1.62.1", + "pptxgenjs": "^4.0.1", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "react-icons": "^5.7.0", + "sharp": "^0.35.4" + } +} diff --git a/server/pom.xml b/server/pom.xml new file mode 100644 index 0000000..e2b3316 --- /dev/null +++ b/server/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.16 + + + + cn.alphaline + ManuAgent-server + 0.1.0-SNAPSHOT + Smart Factory Approval Agent + + + 21 + 2.0.1 + 3.2.3 + 1.21.4 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.flywaydb + flyway-database-postgresql + + + org.postgresql + postgresql + runtime + + + org.apache.tika + tika-core + ${tika.version} + + + io.agentscope + agentscope-harness + ${agentscope.version} + + + io.agentscope + agentscope-extensions-model-openai + ${agentscope.version} + + + io.agentscope + agentscope-extensions-agui + ${agentscope.version} + + + io.agentscope + agentscope-extensions-skill-postgresql-repository + ${agentscope.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/server/src/main/java/cn/alphaline/smartfactory/SmartFactoryApplication.java b/server/src/main/java/cn/alphaline/smartfactory/SmartFactoryApplication.java new file mode 100644 index 0000000..38c82d2 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/SmartFactoryApplication.java @@ -0,0 +1,24 @@ +package cn.alphaline.smartfactory; + +import cn.alphaline.smartfactory.config.AppProperties; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +/** + * 智造申报 Agent 服务入口。 + */ +@SpringBootApplication +@EnableConfigurationProperties(AppProperties.class) +public class SmartFactoryApplication { + + /** + * 启动 Spring Boot 应用。 + * + * @param args 命令行参数 + */ + public static void main(String[] args) { + SpringApplication.run(SmartFactoryApplication.class, args); + } +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentController.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentController.java new file mode 100644 index 0000000..fd7fa41 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentController.java @@ -0,0 +1,141 @@ +package cn.alphaline.smartfactory.agent; + +import com.fasterxml.jackson.databind.JsonNode; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; + +/** + * 提供可恢复的 Agent Run 与 AG-UI 事件流接口。 + */ +@RestController +@RequestMapping("/api/projects/{projectId}") +public class AgentController { + + private final AgentRunService runService; + private final AgentEventService eventService; + + /** + * 创建 Agent 控制器。 + * + * @param runService Run 服务 + * @param eventService 事件服务 + */ + public AgentController(AgentRunService runService, AgentEventService eventService) { + this.runService = runService; + this.eventService = eventService; + } + + /** + * 启动材料检验与规划 Run。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return Run + */ + @PostMapping("/runs/material-check") + public AgentRunService.RunView startMaterialCheck(@PathVariable UUID projectId, Principal principal) { + return runService.startMaterialCheck(projectId, principal); + } + + /** + * 确认材料检验结果并进入规划生成。 + * + * @param projectId 项目 ID + * @param response 材料缺口处理结果 + * @param principal 当前用户 + * @return 规划 Run + */ + @PostMapping("/material/confirm") + public AgentRunService.RunView confirmMaterials( + @PathVariable UUID projectId, + @RequestBody JsonNode response, + Principal principal) { + return runService.confirmMaterials(projectId, response, principal); + } + + /** + * 启动确认后的自动编写 Run。 + * + * @param projectId 项目 ID + * @return Run + */ + @PostMapping("/runs/writing") + public AgentRunService.RunView startWriting(@PathVariable UUID projectId) { + return runService.startWriting(projectId); + } + + /** + * 立即停止当前 Agent Run。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return 已中断 Run + */ + @PostMapping("/runs/stop") + public AgentRunService.RunView stop(@PathVariable UUID projectId, Principal principal) { + return runService.stop(projectId, principal); + } + + /** + * 从已中断位置继续 Agent Run。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return 新恢复 Run + */ + @PostMapping("/runs/resume") + public AgentRunService.RunView resume(@PathVariable UUID projectId, Principal principal) { + return runService.resume(projectId, principal); + } + + /** + * 返回最近 Run。 + * + * @param projectId 项目 ID + * @return 最近 Run;不存在时返回 204 + */ + @GetMapping("/runs/latest") + public ResponseEntity latest(@PathVariable UUID projectId) { + AgentRunService.RunView run = runService.latest(projectId); + return run == null ? ResponseEntity.noContent().build() : ResponseEntity.ok(run); + } + + /** + * 通过游标读取持久化事件。 + * + * @param projectId 项目 ID + * @param after 最后已接收事件序号 + * @return 增量事件 + */ + @GetMapping("/events") + public List events( + @PathVariable UUID projectId, + @RequestParam(defaultValue = "0") long after) { + return eventService.listAfter(projectId, after, 1000); + } + + /** + * 以 NDJSON 持续输出新增事件;页面刷新可携带游标恢复。 + * + * @param projectId 项目 ID + * @param after 最后已接收事件序号 + * @return 持续增量事件流 + */ + @GetMapping(path = "/events/stream", produces = MediaType.APPLICATION_NDJSON_VALUE) + public Flux stream( + @PathVariable UUID projectId, + @RequestParam(defaultValue = "0") long after) { + return eventService.streamAfter(projectId, after); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentEventService.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentEventService.java new file mode 100644 index 0000000..55d52bc --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentEventService.java @@ -0,0 +1,192 @@ +package cn.alphaline.smartfactory.agent; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.core.scheduler.Schedulers; + +/** + * 持久化并查询项目级 AG-UI 事件。 + */ +@Service +public class AgentEventService { + + private final JdbcClient jdbc; + private final ObjectMapper objectMapper; + private final Map> liveStreams = new ConcurrentHashMap<>(); + + /** + * 创建事件服务。 + * + * @param jdbc JDBC 客户端 + * @param objectMapper JSON 映射器 + */ + public AgentEventService(JdbcClient jdbc, ObjectMapper objectMapper) { + this.jdbc = jdbc; + this.objectMapper = objectMapper; + } + + /** + * 先持久化一个事件,再将其返回给流式接口。 + * + * @param projectId 项目 ID + * @param runId Run ID + * @param eventType AG-UI 事件类型 + * @param payload 事件负载 + * @return 已分配全局序号的事件 + */ + public EventView append(UUID projectId, UUID runId, String eventType, Object payload) { + JsonNode value = objectMapper.valueToTree(payload); + ObjectNode object = value.isObject() + ? (ObjectNode) value + : objectMapper.createObjectNode().set("value", value); + EventView event = jdbc.sql(""" + INSERT INTO app.agent_event(project_id, run_id, event_type, event_id, payload) + VALUES (:projectId, :runId, :eventType, :eventId, CAST(:payload AS jsonb)) + RETURNING id, project_id, run_id, event_type, payload, created_at + """) + .param("projectId", projectId) + .param("runId", runId) + .param("eventType", eventType) + .param("eventId", UUID.randomUUID().toString()) + .param("payload", object.toString()) + .query(this::mapEvent) + .single(); + publishAfterCommit(event); + return event; + } + + /** + * 按游标查询增量事件。 + * + * @param projectId 项目 ID + * @param afterId 排除的最后事件序号 + * @param limit 最大返回数量 + * @return 有序事件 + */ + public List listAfter(UUID projectId, long afterId, int limit) { + return jdbc.sql(""" + SELECT id, project_id, run_id, event_type, payload, created_at + FROM app.agent_event + WHERE project_id = :projectId AND id > :afterId + ORDER BY id + LIMIT :limit + """) + .param("projectId", projectId) + .param("afterId", Math.max(0, afterId)) + .param("limit", Math.clamp(limit, 1, 1000)) + .query(this::mapEvent) + .list(); + } + + /** + * 先回放数据库增量,再持续推送当前进程产生的新事件。 + * + * @param projectId 项目 ID + * @param afterId 排除的最后事件序号 + * @return 带轻量心跳的事件流 + */ + public Flux streamAfter(UUID projectId, long afterId) { + return Flux.defer(() -> { + AtomicLong cursor = new AtomicLong(Math.max(0, afterId)); + Sinks.Many sink = liveStreams.computeIfAbsent( + projectId, ignored -> Sinks.many().replay().limit(2_048)); + Mono> first = queryBatch(projectId, cursor.get()); + Flux backlog = first + .expand(batch -> batch.size() == 1_000 + ? queryBatch(projectId, batch.getLast().id()) + : Mono.empty()) + .flatMapIterable(batch -> batch); + Flux events = Flux.concat(backlog, sink.asFlux()) + .filter(event -> event.id() > cursor.get()) + .doOnNext(event -> cursor.set(event.id())); + Flux heartbeat = Flux.interval(java.time.Duration.ofSeconds(15)) + .map(tick -> new EventView( + 0, + projectId, + null, + "HEARTBEAT", + objectMapper.createObjectNode(), + OffsetDateTime.now())); + return Flux.merge(events, heartbeat) + .doFinally(signal -> { + if (sink.currentSubscriberCount() == 0) { + liveStreams.remove(projectId, sink); + } + }); + }); + } + + private Mono> queryBatch(UUID projectId, long afterId) { + return Mono.fromCallable(() -> listAfter(projectId, afterId, 1_000)) + .subscribeOn(Schedulers.boundedElastic()); + } + + private void publishAfterCommit(EventView event) { + Runnable publish = () -> { + Sinks.Many sink = liveStreams.get(event.projectId()); + if (sink != null) { + Sinks.EmitResult result = sink.tryEmitNext(event); + if (result == Sinks.EmitResult.FAIL_NON_SERIALIZED) { + sink.emitNext(event, Sinks.EmitFailureHandler.busyLooping(java.time.Duration.ofMillis(100))); + } + } + }; + if (TransactionSynchronizationManager.isActualTransactionActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + publish.run(); + } + }); + } else { + publish.run(); + } + } + + private EventView mapEvent(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + try { + return new EventView( + rs.getLong("id"), + rs.getObject("project_id", UUID.class), + rs.getObject("run_id", UUID.class), + rs.getString("event_type"), + objectMapper.readTree(rs.getString("payload")), + rs.getObject("created_at", OffsetDateTime.class)); + } catch (com.fasterxml.jackson.core.JsonProcessingException exception) { + throw new java.sql.SQLException("Agent 事件 JSON 无法解析", exception); + } + } + + /** + * 前端可恢复事件视图。 + * + * @param id 项目全局事件序号 + * @param projectId 项目 ID + * @param runId Run ID;心跳为空 + * @param type 事件类型 + * @param payload AG-UI 事件负载 + * @param createdAt 产生时间 + */ + public record EventView( + long id, + UUID projectId, + UUID runId, + String type, + JsonNode payload, + OffsetDateTime createdAt) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentExecutionService.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentExecutionService.java new file mode 100644 index 0000000..081c026 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentExecutionService.java @@ -0,0 +1,263 @@ +package cn.alphaline.smartfactory.agent; + +import cn.alphaline.smartfactory.project.ProjectFileService; +import cn.alphaline.smartfactory.project.ProjectService; +import cn.alphaline.smartfactory.skill.SkillService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.agentscope.core.agui.event.AguiEvent; +import io.agentscope.core.agui.model.AguiMessage; +import io.agentscope.core.agui.model.RunAgentInput; +import io.agentscope.core.model.ModelHttpException; +import io.agentscope.core.model.transport.HttpTransportException; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import java.util.regex.Pattern; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +/** + * 运行 Harness Agent,并把 AG-UI 增量转换为可恢复事件。 + */ +@Service +public class AgentExecutionService { + + private static final Pattern HOST_PATH = Pattern.compile("/Users/[^\\s\"')]+"); + private static final Pattern API_KEY = Pattern.compile("sk-[A-Za-z0-9_-]{8,}"); + static final int MAX_MODEL_RECONNECTS = 5; + + private final ObjectMapper objectMapper; + private final AgentFactory agentFactory; + private final AgentEventService eventService; + private final ProjectFileService fileService; + private final SkillService skillService; + + /** + * 创建 Agent 执行服务。 + * + * @param objectMapper JSON 映射器 + * @param agentFactory Agent 工厂 + * @param eventService 事件服务 + * @param fileService 工作区服务 + * @param skillService Skill 服务 + */ + public AgentExecutionService( + ObjectMapper objectMapper, + AgentFactory agentFactory, + AgentEventService eventService, + ProjectFileService fileService, + SkillService skillService) { + this.objectMapper = objectMapper; + this.agentFactory = agentFactory; + this.eventService = eventService; + this.fileService = fileService; + this.skillService = skillService; + } + + /** + * 执行一个可停止、可重连的 Agent 流。 + * + * @param project 当前项目 + * @param run 当前 Run + * @param prompt 本轮提示词 + * @param stopSignal 用户停止信号 + * @param ensureRunning 终态检查 + * @param interrupted 中断状态查询 + */ + public void execute( + ProjectService.ProjectView project, + AgentRunService.RunView run, + String prompt, + Mono stopSignal, + Runnable ensureRunning, + BooleanSupplier interrupted) { + EventAccumulator accumulator = new EventAccumulator(project.id(), run.id()); + for (int reconnects = 0; ; reconnects++) { + ensureRunning.run(); + String attemptPrompt = reconnects == 0 ? prompt : """ + 模型连接刚刚中断。请恢复同一线程的会话状态,读取 MEMORY.md 和工作区已有成果, + 检查未完成的输出后从中断处继续;复用已经完成的工具结果,不要重复已完成操作。 + """; + RunAgentInput input = RunAgentInput.builder() + .threadId(project.threadId()) + .runId(run.id().toString()) + .messages(List.of(AguiMessage.userMessage(UUID.randomUUID().toString(), attemptPrompt))) + .build(); + try (AgentFactory.AgentHandle handle = agentFactory.create(project.id(), skillService.enabledNames())) { + handle.adapter().run(input) + .takeUntilOther(stopSignal) + .bufferTimeout(64, Duration.ofMillis(120)) + .doOnNext(accumulator::accept) + .blockLast(); + accumulator.flush(); + ensureRunning.run(); + return; + } catch (RuntimeException exception) { + accumulator.flush(); + if (interrupted.getAsBoolean()) { + throw new RunInterruptedException(); + } + if (reconnects >= MAX_MODEL_RECONNECTS || !isRetryableModelFailure(exception)) { + throw exception; + } + int attempt = reconnects + 1; + eventService.append(project.id(), run.id(), "MODEL_RETRY", Map.of( + "attempt", attempt, "maxAttempts", MAX_MODEL_RECONNECTS)); + pauseBeforeReconnect(attempt, interrupted); + } + } + } + + /** + * 判断异常链是否属于可重试的模型连接故障。 + * + * @param failure 模型调用异常 + * @return 是否允许重连 + */ + static boolean isRetryableModelFailure(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof HttpTransportException transport && transport.isRetryable()) { + return true; + } + if (current instanceof ModelHttpException http && http.isRetryableHttpStatus()) { + return true; + } + if (current.getCause() == current) { + break; + } + current = current.getCause(); + } + return false; + } + + private void pauseBeforeReconnect(int attempt, BooleanSupplier interrupted) { + try { + Thread.sleep(Math.min(8_000L, 500L << (attempt - 1))); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + if (interrupted.getAsBoolean()) { + throw new RunInterruptedException(); + } + throw new IllegalStateException("模型重连等待被中断", exception); + } + } + + /** + * 标识正常的用户中断。 + */ + static final class RunInterruptedException extends RuntimeException { + } + + /** + * 跨 Reactor 批次合并连续 token,并过滤 Adapter 自带的重复生命周期事件。 + */ + private final class EventAccumulator { + + private final UUID projectId; + private final UUID runId; + private ObjectNode pending; + private String pendingType; + private String pendingKey; + private String pendingField; + private long lastFlushNanos = System.nanoTime(); + + private EventAccumulator(UUID projectId, UUID runId) { + this.projectId = projectId; + this.runId = runId; + } + + private void accept(List batch) { + for (AguiEvent event : batch) { + accept(event); + } + if (System.nanoTime() - lastFlushNanos >= Duration.ofMillis(400).toNanos()) { + flush(); + } + } + + private void accept(AguiEvent event) { + String type = event.getType().name(); + if (type.equals("RUN_STARTED") || type.equals("RUN_FINISHED") || type.equals("RUN_ERROR")) { + return; + } + ObjectNode payload = (ObjectNode) sanitize( + objectMapper.valueToTree(event), fileService.projectRoot(projectId).toString()); + if (type.equals("TOOL_CALL_RESULT") && payload.path("content").isTextual()) { + payload.put("content", stripInlineImageData(payload.path("content").asText())); + } + String field = switch (type) { + case "TEXT_MESSAGE_CONTENT", "TEXT_MESSAGE_CHUNK", + "REASONING_MESSAGE_CONTENT", "REASONING_MESSAGE_CHUNK" -> + payload.has("delta") ? "delta" : "content"; + case "TOOL_CALL_ARGS", "TOOL_CALL_CHUNK" -> payload.has("delta") ? "delta" : "args"; + default -> null; + }; + String key = payload.path("messageId").asText(payload.path("toolCallId").asText("")); + if (field != null && pending != null && type.equals(pendingType) + && key.equals(pendingKey) && field.equals(pendingField)) { + pending.put(field, pending.path(field).asText() + payload.path(field).asText()); + return; + } + flush(); + if (field == null) { + eventService.append(projectId, runId, type, payload); + } else { + pending = payload; + pendingType = type; + pendingKey = key; + pendingField = field; + } + } + + private JsonNode sanitize(JsonNode node, String workspaceRoot) { + if (node.isTextual()) { + String text = node.textValue().replace(workspaceRoot, "工作区"); + text = HOST_PATH.matcher(text).replaceAll("内部路径"); + return objectMapper.getNodeFactory().textNode(API_KEY.matcher(text).replaceAll("已隐藏凭证")); + } + if (node instanceof ObjectNode object) { + object.properties().forEach(entry -> object.set( + entry.getKey(), sanitize(entry.getValue(), workspaceRoot))); + } else if (node instanceof ArrayNode array) { + for (int index = 0; index < array.size(); index++) { + array.set(index, sanitize(array.get(index), workspaceRoot)); + } + } + return node; + } + + private void flush() { + if (pending != null) { + eventService.append(projectId, runId, pendingType, pending); + pending = null; + pendingType = null; + pendingKey = null; + pendingField = null; + } + lastFlushNanos = System.nanoTime(); + } + } + + /** + * 从持久化 AG-UI 工具结果中移除已经传给模型的 Base64 图片,保留结构化文本元数据。 + * + * @param content AG-UI 工具结果文本 + * @return 适合数据库与浏览器恢复的精简结果 + */ + static String stripInlineImageData(String content) { + int imageStart = content.indexOf("\n{\"type\":\"image\""); + if (content.startsWith("document_view_result=") && imageStart > 0) { + return content.substring(0, imageStart); + } + return content.lines() + .filter(line -> !((line.contains("\"mediaType\"") || line.contains("\"media_type\"")) + && line.contains("\"data\""))) + .collect(java.util.stream.Collectors.joining("\n")); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentFactory.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentFactory.java new file mode 100644 index 0000000..c4416d2 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentFactory.java @@ -0,0 +1,320 @@ +package cn.alphaline.smartfactory.agent; + +import cn.alphaline.smartfactory.config.AppProperties; +import cn.alphaline.smartfactory.model.ModelService; +import cn.alphaline.smartfactory.project.ProjectFileService; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.agentscope.core.agui.adapter.AguiAdapterConfig; +import io.agentscope.core.agui.adapter.AguiAgentAdapter; +import io.agentscope.core.skill.AgentSkill; +import io.agentscope.core.skill.repository.AgentSkillRepository; +import io.agentscope.core.skill.repository.AgentSkillRepositoryInfo; +import io.agentscope.core.skill.repository.postgresql.PostgresSkillRepository; +import io.agentscope.core.tool.Toolkit; +import io.agentscope.extensions.model.openai.OpenAIChatModel; +import io.agentscope.harness.agent.IsolationScope; +import io.agentscope.harness.agent.HarnessAgent; +import io.agentscope.harness.agent.memory.compaction.CompactionConfig; +import io.agentscope.harness.agent.memory.compaction.ToolResultEvictionConfig; +import io.agentscope.harness.agent.sandbox.WorkspaceSpec; +import io.agentscope.harness.agent.sandbox.impl.docker.DockerFilesystemSpec; +import io.agentscope.harness.agent.sandbox.layout.BindMountEntry; +import io.agentscope.harness.agent.sandbox.layout.WorkspaceEntry; +import io.agentscope.harness.agent.sandbox.snapshot.LocalSnapshotSpec; +import io.agentscope.harness.agent.workspace.WorkspacePathNormalizer; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; + +/** + * 按当前模型、Skill 和项目工作区创建短生命周期 Harness Agent。 + */ +@Component +public class AgentFactory { + + private final ModelService modelService; + private final PostgresSkillRepository skillRepository; + private final ProjectFileService fileService; + private final AppProperties properties; + private final ObjectMapper objectMapper; + private final String systemPrompt; + private final String compactionPrompt; + + /** + * 创建 Agent 工厂。 + * + * @param modelService 模型配置服务 + * @param skillRepository AgentScope Skill 仓库 + * @param fileService 项目工作区服务 + * @param properties 应用配置 + * @param objectMapper JSON 映射器 + */ + public AgentFactory( + ModelService modelService, + PostgresSkillRepository skillRepository, + ProjectFileService fileService, + AppProperties properties, + ObjectMapper objectMapper) { + this.modelService = modelService; + this.skillRepository = skillRepository; + this.fileService = fileService; + this.properties = properties; + this.objectMapper = objectMapper; + this.systemPrompt = readPrompt("prompts/smart-factory-agent-system.md", "Agent 全局提示词"); + this.compactionPrompt = readPrompt("prompts/smart-factory-compaction.md", "上下文压缩提示词"); + } + + /** + * 创建开启 AG-UI 推理和工具事件的 Harness 适配器。 + * + * @param projectId 项目 ID + * @param enabledSkills 当前启用 Skill + * @return 需要在流结束后关闭的 Agent 句柄 + */ + public AgentHandle create(UUID projectId, String[] enabledSkills) { + ModelService.ModelSecret model = modelService.defaultModelSecret(); + OpenAIChatModel chatModel = OpenAIChatModel.builder() + .apiKey(model.apiKey()) + .baseUrl(model.baseUrl()) + .modelName(model.modelId()) + .stream(true) + .build(); + fileService.ensureWorkspace(projectId); + Path projectRoot = fileService.projectRoot(projectId); + Map environment = new HashMap<>(); + environment.put("DASHSCOPE_API_KEY", readOptionalKey(properties.dashscopeKeyFile())); + environment.put("PATH", "/opt/java/openjdk/bin:/usr/local/bin:/usr/bin:/bin"); + environment.put("NODE_PATH", "/opt/agent-runtime/node_modules"); + environment.put("SKILL_SESSION_ID", "project-" + projectId); + + WorkspaceSpec workspace = new WorkspaceSpec(); + Map entries = new LinkedHashMap<>(); + entries.put("inputs", mount(projectRoot.resolve("inputs"), true)); + entries.put("work", mount(projectRoot.resolve("work"), false)); + entries.put("references", mount(projectRoot.resolve("references"), false)); + entries.put("artifacts", mount(projectRoot.resolve("work/candidates"), false)); + workspace.setEntries(entries); + workspace.setEnvironment(environment); + + Path snapshotRoot = properties.dataRoot().toAbsolutePath().normalize().resolve("sandbox-snapshots"); + try { + Files.createDirectories(snapshotRoot); + } catch (IOException exception) { + throw new IllegalStateException("无法创建 Agent 沙箱快照目录", exception); + } + DockerFilesystemSpec filesystem = new DockerFilesystemSpec() + .image(properties.sandboxImage()) + .workspaceRoot("/workspace") + .environment(environment) + .memorySizeBytes(2L * 1024 * 1024 * 1024) + .cpuCount(2L) + .exposedPorts() + .network(properties.sandboxNetwork()) + .additionalRunArgs( + "--pids-limit=256", + "--cap-drop=ALL", + "--security-opt=no-new-privileges", + "--stop-signal=SIGKILL") + .snapshotSpec(new LocalSnapshotSpec(snapshotRoot)) + .workspaceSpec(workspace); + filesystem.isolationScope(IsolationScope.SESSION); + + CompactionConfig compaction = compactionFor(model.contextWindow(), compactionPrompt); + Toolkit toolkit = new Toolkit(); + DocumentViewTool documentView = new DocumentViewTool(objectMapper); + toolkit.registerTool(documentView); + HarnessAgent agent = HarnessAgent.builder() + .name("smart-factory-agent") + .description("智能工厂申报书规划、编写与评审 Agent") + .sysPrompt(systemPrompt) + .model(chatModel) + .toolkit(toolkit) + .workspace(projectRoot) + .filesystem(filesystem) + .skillRepository(new EnabledSkillRepository(skillRepository, Set.copyOf(Arrays.asList(enabledSkills)))) + .compaction(compaction) + .toolResultEviction(ToolResultEvictionConfig.defaults()) + .maxContextTokens(model.contextWindow()) + .maxIters(96) + .enableAgentTracingLog(false) + .disableSubagents() + .build(); + agent.getToolkit().registerTool(new PagedReadFileTool( + agent.getWorkspaceManager().getFilesystem(), + WorkspacePathNormalizer.of("/workspace"), + objectMapper)); + documentView.bind(agent); + AguiAdapterConfig config = AguiAdapterConfig.builder() + .enableReasoning(true) + .emitToolCallArgs(true) + .emitStateEvents(false) + .runTimeout(properties.runTimeout()) + .defaultAgentId("smart-factory-agent") + .build(); + return new AgentHandle(new AguiAgentAdapter(agent, config), agent); + } + + /** + * 按模型窗口构造仅由 Token 触发的压缩配置。 + * + * @param contextWindow 模型上下文窗口 + * @param summaryPrompt 压缩摘要约束 + * @return AgentScope 压缩配置 + */ + static CompactionConfig compactionFor(int contextWindow, String summaryPrompt) { + int triggerTokens = Math.max(1, (int) Math.floor(contextWindow * 0.90d)); + int keepTokensMin = Math.max(1_024, Math.min(4_000, contextWindow / 8)); + int keepTokensMax = Math.max(keepTokensMin, Math.min(16_000, contextWindow / 5)); + return CompactionConfig.builder() + .triggerMessages(0) + .triggerTokens(triggerTokens) + .reserved(Math.max(1_024, contextWindow / 10)) + .keepTokensMin(keepTokensMin) + .keepTokensMax(keepTokensMax) + .keepTokensRatio(0.18d) + .summaryPrompt(summaryPrompt) + .flushBeforeCompact(true) + .offloadBeforeCompact(true) + .build(); + } + + /** + * 将 AgentScope 默认的 name_source Skill ID 规范化为业务名称,同时保留完整 Skill 信息。 + * + * @param skill 仓库返回的 Skill + * @return 使用业务名称作为调用 ID 的 Skill + */ + static AgentSkill canonicalSkill(AgentSkill skill) { + return new AgentSkill( + skill.getMetadata(), + skill.getSkillContent(), + skill.getResources(), + skill.getSource(), + skill.getOriginDir().orElse(null)) { + /** {@inheritDoc} */ + @Override + public String getSkillId() { + return getName(); + } + }; + } + + private BindMountEntry mount(Path hostPath, boolean readOnly) { + BindMountEntry entry = new BindMountEntry(); + entry.setHostPath(hostPath.toAbsolutePath().normalize().toString()); + entry.setReadOnly(readOnly); + return entry; + } + + private String readPrompt(String path, String label) { + try { + return new ClassPathResource(path) + .getContentAsString(StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException("无法读取" + label, exception); + } + } + + private String readOptionalKey(java.nio.file.Path path) { + try { + return Files.isRegularFile(path) ? Files.readString(path, StandardCharsets.UTF_8).trim() : ""; + } catch (IOException exception) { + throw new IllegalStateException("无法读取百炼知识库 Key", exception); + } + } + + /** + * 绑定 AG-UI 适配器与其拥有的沙箱 Agent 生命周期。 + * + * @param adapter AG-UI 适配器 + * @param agent Harness Agent + */ + public record AgentHandle(AguiAgentAdapter adapter, HarnessAgent agent) implements AutoCloseable { + + /** + * 结束 Agent 并释放 Docker 沙箱资源。 + */ + @Override + public void close() { + agent.close(); + } + } + + /** + * 只向 Agent 暴露管理员启用的 Skill,所有写操作继续委托原仓库。 + */ + private static final class EnabledSkillRepository implements AgentSkillRepository { + + private final AgentSkillRepository delegate; + private final Set enabled; + + private EnabledSkillRepository(AgentSkillRepository delegate, Set enabled) { + this.delegate = delegate; + this.enabled = enabled; + } + + @Override + public AgentSkill getSkill(String name) { + AgentSkill skill = enabled.contains(name) ? delegate.getSkill(name) : null; + return skill == null ? null : canonicalSkill(skill); + } + + @Override + public List getAllSkillNames() { + return delegate.getAllSkillNames().stream().filter(enabled::contains).toList(); + } + + @Override + public List getAllSkills() { + return delegate.getAllSkills().stream() + .filter(skill -> enabled.contains(skill.getName())) + .map(AgentFactory::canonicalSkill) + .toList(); + } + + @Override + public boolean save(List skills, boolean overwrite) { + return delegate.save(skills, overwrite); + } + + @Override + public boolean delete(String name) { + return delegate.delete(name); + } + + @Override + public boolean skillExists(String name) { + return enabled.contains(name) && delegate.skillExists(name); + } + + @Override + public AgentSkillRepositoryInfo getRepositoryInfo() { + return delegate.getRepositoryInfo(); + } + + @Override + public String getSource() { + return delegate.getSource(); + } + + @Override + public void setWriteable(boolean writeable) { + delegate.setWriteable(writeable); + } + + @Override + public boolean isWriteable() { + return delegate.isWriteable(); + } + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentOutputService.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentOutputService.java new file mode 100644 index 0000000..ad45305 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentOutputService.java @@ -0,0 +1,179 @@ +package cn.alphaline.smartfactory.agent; + +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.project.ProjectFileService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.IntSummaryStatistics; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +/** + * 读取并校验 Agent 交给业务流程的结构化文件。 + */ +@Service +public class AgentOutputService { + + private static final Pattern YEAR_RANGE = Pattern.compile("(20\\d{2})\\D+(20\\d{2})"); + private static final Pattern NUMBER = Pattern.compile("(\\d+)"); + + private final ObjectMapper objectMapper; + private final ProjectFileService fileService; + + /** + * 创建 Agent 输出服务。 + * + * @param objectMapper JSON 映射器 + * @param fileService 工作区服务 + */ + public AgentOutputService(ObjectMapper objectMapper, ProjectFileService fileService) { + this.objectMapper = objectMapper; + this.fileService = fileService; + } + + /** + * 读取并校验材料检验结果。 + * + * @param projectId 项目 ID + * @return 材料检验对象 + * @throws IOException 文件无法读取时抛出 + */ + public ObjectNode readMaterialCheck(UUID projectId) throws IOException { + Path path = fileService.safeProjectPath(projectId, "work/facts/material-check.json"); + if (!Files.isRegularFile(path)) { + throw new ApiException( + HttpStatus.UNPROCESSABLE_ENTITY, + "MATERIAL_CHECK_MISSING", + "Agent 未生成材料检验结果,请重试"); + } + JsonNode value = objectMapper.readTree(path.toFile()); + if (!(value instanceof ObjectNode report) + || !hasText(report, "summary") + || !report.path("completeness").canConvertToInt() + || !report.path("confirmedFacts").isArray() + || !report.path("missingItems").isArray()) { + throw new ApiException( + HttpStatus.UNPROCESSABLE_ENTITY, + "MATERIAL_CHECK_INVALID", + "Agent 生成的材料检验结果结构不完整,请重试"); + } + return report; + } + + /** + * 读取并校验 Agent 建议规划。 + * + * @param projectId 项目 ID + * @return 建设规划对象 + * @throws IOException 文件无法读取时抛出 + */ + public ObjectNode readProposedPlan(UUID projectId) throws IOException { + Path path = fileService.safeProjectPath(projectId, "work/plans/proposed-plan.json"); + if (!Files.isRegularFile(path)) { + throw new ApiException( + HttpStatus.UNPROCESSABLE_ENTITY, + "PLAN_OUTPUT_MISSING", + "Agent 未生成结构化建设规划,请重试材料检验"); + } + JsonNode value = objectMapper.readTree(path.toFile()); + if (!(value instanceof ObjectNode plan)) { + throw invalidPlan(); + } + normalizePlanningYears(plan); + if (!hasText(plan, "coreDirection") + || !hasText(plan, "collaborationDirection") + || !hasText(plan, "factoryName") + || !plan.path("planningYears").canConvertToInt() + || !hasText(plan, "investmentRange") + || !hasText(plan, "applicationLevel") + || !plan.path("scenarios").isArray() + || plan.path("scenarios").isEmpty() + || !plan.path("aiScenarioCount").canConvertToInt() + || !plan.path("assumptions").isArray()) { + throw invalidPlan(); + } + plan.put("scenarioCount", plan.path("scenarios").size()); + return plan; + } + + /** + * 校验用户确认后的规划满足编写最小结构。 + * + * @param plan 用户确认规划 + */ + public void validateConfirmedPlan(JsonNode plan) { + if (plan == null || !plan.isObject() + || !hasText(plan, "coreDirection") + || !hasText(plan, "collaborationDirection") + || !hasText(plan, "factoryName") + || !plan.path("planningYears").canConvertToInt() + || plan.path("planningYears").asInt() < 1 + || !hasText(plan, "investmentRange") + || !plan.path("scenarioCount").canConvertToInt() + || plan.path("scenarioCount").asInt() < 1 + || !plan.path("aiScenarioCount").canConvertToInt() + || plan.path("aiScenarioCount").asInt() < 0 + || plan.path("aiScenarioCount").asInt() > plan.path("scenarioCount").asInt()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "PLAN_INVALID", "请完整填写并检查建设规划"); + } + } + + /** + * 将模型可能输出的年份数组或文本区间归一化为规划年数。 + * + * @param plan 待归一化的规划对象 + */ + static void normalizePlanningYears(ObjectNode plan) { + JsonNode value = plan.path("planningYears"); + if (value.canConvertToInt()) { + return; + } + if (value.isArray()) { + IntSummaryStatistics years = new IntSummaryStatistics(); + value.forEach(year -> { + Matcher matcher = NUMBER.matcher(year.asText()); + if (matcher.find()) { + years.accept(Integer.parseInt(matcher.group(1))); + } + }); + if (years.getCount() > 0) { + plan.put("planningPeriod", years.getMin() == years.getMax() + ? Integer.toString(years.getMin()) + : years.getMin() + "-" + years.getMax()); + plan.put("planningYears", years.getMax() - years.getMin() + 1); + } + return; + } + String text = value.asText(); + Matcher range = YEAR_RANGE.matcher(text); + if (range.find()) { + int years = Integer.parseInt(range.group(2)) - Integer.parseInt(range.group(1)) + 1; + plan.put("planningPeriod", text); + plan.put("planningYears", Math.max(1, years)); + return; + } + Matcher number = NUMBER.matcher(text); + if (number.find()) { + plan.put("planningPeriod", text); + plan.put("planningYears", Math.max(1, Integer.parseInt(number.group(1)))); + } + } + + private boolean hasText(JsonNode value, String field) { + return value.path(field).isTextual() && !value.path(field).asText().isBlank(); + } + + private ApiException invalidPlan() { + return new ApiException( + HttpStatus.UNPROCESSABLE_ENTITY, + "PLAN_OUTPUT_INVALID", + "Agent 生成的建设规划结构不完整,请重试材料检验"); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunService.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunService.java new file mode 100644 index 0000000..d5c3bea --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunService.java @@ -0,0 +1,684 @@ +package cn.alphaline.smartfactory.agent; + +import cn.alphaline.smartfactory.artifact.ArtifactService; +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.project.ProjectFileService; +import cn.alphaline.smartfactory.project.ProjectService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.security.Principal; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import reactor.core.publisher.Sinks; + +/** + * 驱动材料检验、规划 Ask 和自动编写 Run。 + */ +@Service +public class AgentRunService { + + private static final Logger log = LoggerFactory.getLogger(AgentRunService.class); + private final JdbcClient jdbc; + private final ObjectMapper objectMapper; + private final AgentExecutionService executionService; + private final AgentOutputService outputService; + private final AgentRunStore runStore; + private final AgentEventService eventService; + private final ProjectService projectService; + private final ProjectFileService fileService; + private final UserService userService; + private final ArtifactService artifactService; + private final ExecutorService executor; + private final TransactionTemplate transactions; + private final ConcurrentMap activeRuns = new ConcurrentHashMap<>(); + + /** + * 创建 Agent Run 服务。 + * + * @param jdbc JDBC 客户端 + * @param objectMapper JSON 映射器 + * @param executionService Agent 执行服务 + * @param outputService Agent 结构化输出服务 + * @param runStore Run 状态存储 + * @param eventService 事件服务 + * @param projectService 项目服务 + * @param fileService 材料与工作区服务 + * @param userService 用户服务 + * @param artifactService 产物服务 + * @param applicationExecutor 虚拟线程执行器 + * @param transactions 编程式事务模板 + */ + public AgentRunService( + JdbcClient jdbc, + ObjectMapper objectMapper, + AgentExecutionService executionService, + AgentOutputService outputService, + AgentRunStore runStore, + AgentEventService eventService, + ProjectService projectService, + ProjectFileService fileService, + UserService userService, + ArtifactService artifactService, + ExecutorService applicationExecutor, + TransactionTemplate transactions) { + this.jdbc = jdbc; + this.objectMapper = objectMapper; + this.executionService = executionService; + this.outputService = outputService; + this.runStore = runStore; + this.eventService = eventService; + this.projectService = projectService; + this.fileService = fileService; + this.userService = userService; + this.artifactService = artifactService; + this.executor = applicationExecutor; + this.transactions = transactions; + } + + /** + * 后台启动材料检验。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return 新 Run + */ + @Transactional + public RunView startMaterialCheck(UUID projectId, Principal principal) { + ProjectService.ProjectView project = projectService.require(projectId); + userService.requireUserId(principal.getName()); + RunView run = runStore.create(projectId, "INITIAL", null); + projectService.updateStatus(projectId, "MATERIAL_CHECK"); + afterCommit(run.id(), () -> executeMaterialRun(project, run, false)); + return run; + } + + /** + * 确认材料检验结果并后台生成建设规划。 + * + * @param projectId 项目 ID + * @param response 用户对材料缺口的处理结果 + * @param principal 当前用户 + * @return 新规划 Run + */ + @Transactional + public RunView confirmMaterials(UUID projectId, JsonNode response, Principal principal) { + ProjectService.ProjectView project = projectService.require(projectId); + UUID userId = userService.requireUserId(principal.getName()); + RunView waiting = runStore.requireWaiting(projectId, "material_check"); + if (!response.isObject() || !response.path("decisions").isArray()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "MATERIAL_RESPONSE_INVALID", "请确认每项材料缺口"); + } + eventService.append(projectId, waiting.id(), "ASK_RESPONDED", response); + runStore.completeWaiting(waiting.id()); + RunView run = runStore.create(projectId, "RESUME", waiting.id()); + projectService.updateStatus(projectId, "PLANNING"); + afterCommit(run.id(), () -> executePlanningRun(project, run, userId, response, false)); + return run; + } + + /** + * 在一个事务中确认规划并启动自动编写,重复提交返回既有结果。 + * + * @param projectId 项目 ID + * @param planId 规划 ID + * @param confirmedPlan 用户确认后的规划 + * @param principal 当前用户 + * @return 已确认规划及编写 Run + */ + @Transactional + public ConfirmPlanResult confirmPlanAndStartWriting( + UUID projectId, + UUID planId, + JsonNode confirmedPlan, + Principal principal) { + ProjectService.ProjectView project = projectService.require(projectId); + ProjectService.PlanView current = projectService.currentPlan(projectId); + if (current != null && current.id().equals(planId) && "CONFIRMED".equals(current.status())) { + RunView existing = latest(projectId); + if (existing != null && !"WAITING_INPUT".equals(existing.status())) { + return new ConfirmPlanResult(current, existing); + } + } + outputService.validateConfirmedPlan(confirmedPlan); + RunView waiting = runStore.requireWaiting(projectId, "planning"); + ProjectService.PlanView plan = projectService.confirmPlan(projectId, planId, confirmedPlan, principal); + eventService.append(projectId, waiting.id(), "ASK_RESPONDED", Map.of("planId", planId)); + runStore.completeWaiting(waiting.id()); + RunView run = runStore.create(projectId, "RESUME", waiting.id()); + afterCommit(run.id(), () -> executeWritingRun(project, plan, run, false)); + return new ConfirmPlanResult(plan, run); + } + + /** + * 恢复已确认但尚未完成的自动编写任务。 + * + * @param projectId 项目 ID + * @return 编写 Run + */ + @Transactional + public RunView startWriting(UUID projectId) { + ProjectService.ProjectView project = projectService.require(projectId); + ProjectService.PlanView plan = projectService.currentPlan(projectId); + if (plan == null || !"CONFIRMED".equals(plan.status())) { + throw new ApiException(HttpStatus.CONFLICT, "PLAN_NOT_CONFIRMED", "请先确认建设规划"); + } + RunView latest = latest(projectId); + if (latest != null && "RUNNING".equals(latest.status())) { + return latest; + } + if (latest != null && "WAITING_INPUT".equals(latest.status())) { + runStore.completeWaiting(latest.id()); + } + RunView run = runStore.create(projectId, "RESUME", latest == null ? null : latest.id()); + projectService.updateStatus(projectId, "WRITING"); + afterCommit(run.id(), () -> executeWritingRun(project, plan, run, false)); + return run; + } + + /** + * 立即停止当前 Run,并保留项目阶段和工作区成果。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return 已中断的 Run + */ + @Transactional + public RunView stop(UUID projectId, Principal principal) { + projectService.require(projectId); + userService.requireUserId(principal.getName()); + RunView run = latest(projectId); + if (run == null || !"RUNNING".equals(run.status())) { + throw new ApiException(HttpStatus.CONFLICT, "RUN_NOT_ACTIVE", "当前没有正在执行的任务"); + } + int updated = jdbc.sql(""" + UPDATE app.agent_run + SET status = 'INTERRUPTED', pending_interrupt = NULL, + error_code = 'USER_STOPPED', error_message = '用户已停止运行', + ended_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE id = :id AND status = 'RUNNING' + """) + .param("id", run.id()) + .update(); + requireTerminalUpdate(updated); + eventService.append(projectId, run.id(), "RUN_FINISHED", Map.of("outcome", "CANCELLED")); + onCommit(() -> { + RunControl control = activeRuns.get(run.id()); + if (control != null) { + control.cancel(); + } + }); + return runStore.require(run.id()); + } + + /** + * 从已中断 Run 的原阶段继续,复用同一线程状态和工作区成果。 + * + * @param projectId 项目 ID + * @param principal 当前用户 + * @return 新的恢复 Run + */ + @Transactional + public RunView resume(UUID projectId, Principal principal) { + ProjectService.ProjectView project = projectService.require(projectId); + UUID userId = userService.requireUserId(principal.getName()); + RunView interrupted = latest(projectId); + if (interrupted == null || !"INTERRUPTED".equals(interrupted.status())) { + throw new ApiException(HttpStatus.CONFLICT, "RUN_NOT_INTERRUPTED", "当前没有可继续的任务"); + } + String phase = runStore.interruptedPhase(interrupted, project); + RunView run = runStore.create(projectId, "RESUME", interrupted.id()); + projectService.updateStatus(projectId, phase); + switch (phase) { + case "MATERIAL_CHECK" -> afterCommit( + run.id(), () -> executeMaterialRun(project, run, true)); + case "PLANNING" -> { + JsonNode materialResponse = runStore.latestMaterialResponse(projectId); + afterCommit(run.id(), () -> executePlanningRun( + project, run, userId, materialResponse, true)); + } + case "WRITING" -> { + ProjectService.PlanView plan = projectService.currentPlan(projectId); + if (plan == null || !"CONFIRMED".equals(plan.status())) { + throw new ApiException(HttpStatus.CONFLICT, "PLAN_NOT_CONFIRMED", "无法恢复:建设规划尚未确认"); + } + afterCommit(run.id(), () -> executeWritingRun(project, plan, run, true)); + } + default -> throw new ApiException( + HttpStatus.CONFLICT, "RUN_PHASE_UNKNOWN", "无法识别中断前的执行阶段"); + } + return run; + } + + /** + * 返回项目最近一次 Run。 + * + * @param projectId 项目 ID + * @return Run;未执行时为空 + */ + public RunView latest(UUID projectId) { + return runStore.latest(projectId); + } + + private void executeMaterialRun(ProjectService.ProjectView project, RunView run, boolean resuming) { + try { + eventService.append(project.id(), run.id(), "RUN_STARTED", Map.of( + "threadId", project.threadId(), "runId", run.id(), "phase", "MATERIAL_CHECK")); + List files = fileService.list(project.id()); + String fileSummary = files.isEmpty() + ? "没有企业材料,当前仅有企业名称。" + : files.stream().map(file -> file.relativePath() + "(" + file.extension() + ")") + .collect(java.util.stream.Collectors.joining("、")); + String prompt = """ + 现在只执行材料检验。企业:%s;申报等级:%s。 + 已上传材料:%s + 请递归读取 inputs/ 下材料,先调用相应文档 Skill,再调用企业画像、材料诊断与知识库 Skill,输出简洁的事实与缺口摘要。 + 若结构化读取无法覆盖扫描页、流程图或关键版面,可按需调用 document_view;不要默认渲染全部页面。 + 材料存在时不得虚构材料事实;知识库内容只能补充背景、政策和规划依据,不能冒充企业事实。 + 完成首轮目录清点后,先创建满足下述结构的 JSON 初稿,再在读取过程中持续更新,避免把必需产物留到最后。 + 结束前必须把检验结果写入 work/facts/material-check.json,使用 UTF-8 严格 JSON,不能包含 Markdown。 + JSON 必须包含 summary、completeness(0-100 整数)、confirmedFacts(字符串数组)和 missingItems(对象数组)。 + 每个 missingItems 对象必须包含 id、label、reason、required。即使仅有企业名称,也要给出可继续规划的最小缺口清单。 + 暂时不要生成建设规划或 DOCX。 + 完成后仅输出材料覆盖、已确认事实和待确认缺口,不说明内部文件、格式、工具、命令、落盘或校验过程。 + """.formatted(project.companyName(), project.applicationLevel(), fileSummary); + streamAgent(project, run, recoveryPrompt(prompt, resuming)); + ObjectNode report = readMaterialCheckWithRepair(project, run); + ObjectNode ask = objectMapper.createObjectNode(); + ask.put("kind", "material_check"); + ask.put("interruptId", "materials-" + run.id()); + ask.put("title", "确认材料检验"); + ask.put("description", "确认缺口处理方式后生成建设规划"); + ask.set("report", report); + finishWaiting(project.id(), run.id(), ask); + } catch (Exception exception) { + failUnlessInterrupted(run, exception); + } + } + + /** + * 读取材料检验结果;Agent 正常结束但未写出有效文件时,把校验错误反馈给同一线程继续修复。 + * + * @param project 当前项目 + * @param run 当前 Run + * @return 有效材料检验结果 + * @throws IOException 修复后产物仍无法读取时抛出 + */ + private ObjectNode readMaterialCheckWithRepair(ProjectService.ProjectView project, RunView run) + throws IOException { + int repairRound = 0; + while (true) { + try { + return outputService.readMaterialCheck(project.id()); + } catch (ApiException | IOException exception) { + runStore.ensureRunning(run.id()); + repairRound++; + log.warn("Agent 未生成有效材料检验结果,继续同一线程修复,runId={},round={}", + run.id(), repairRound, exception); + streamAgent(project, run, """ + 材料检验结构化产物校验失败:%s + 请使用简体中文,优先复用当前上下文及 work/extracted 中已有结果,停止大范围补充探索。 + 立即修复并写入 work/facts/material-check.json,使用 UTF-8 严格 JSON,再调用 read_file 复核。 + 必须包含 summary、completeness、confirmedFacts、missingItems;每个 missingItems 对象必须包含 + id、label、reason、required。完成有效文件后再结束本轮。 + """.formatted(exception.getMessage())); + } + } + } + + /** + * 根据材料确认结果自动生成建设规划并进入规划 Ask。 + * + * @param project 企业项目 + * @param run 当前 Run + * @param userId 当前用户 ID + * @param materialResponse 材料确认结果 + */ + private void executePlanningRun( + ProjectService.ProjectView project, + RunView run, + UUID userId, + JsonNode materialResponse, + boolean resuming) { + try { + eventService.append(project.id(), run.id(), "RUN_STARTED", Map.of( + "threadId", project.threadId(), "runId", run.id(), "phase", "PLANNING")); + String prompt = """ + 现在生成建设规划。企业:%s;申报等级:%s。 + 材料检验确认结果:%s + 请调用知识库、差距分析和建设规划 Skill,自主形成与企业名称、行业线索和申报等级一致的方案。 + 已有企业材料中的事实不得改写或补造;缺少事实时允许使用知识库形成明确标记的规划假设。 + 结束前必须把建议规划写入 work/plans/proposed-plan.json,使用 UTF-8 严格 JSON,不能包含 Markdown。 + JSON 必须包含 coreDirection、collaborationDirection、factoryName、planningYears(1-10 的整数)、investmentRange、 + applicationLevel、scenarios(字符串数组)、aiScenarioCount(整数)和 assumptions(字符串数组)。 + 暂时不要编写最终 DOCX。 + 完成后仅输出用户确认规划所需的方向、周期、投资、场景和假设,不说明内部文件、格式、工具、命令、落盘或校验过程。 + """.formatted(project.companyName(), project.applicationLevel(), materialResponse.toString()); + streamAgent(project, run, recoveryPrompt(prompt, resuming)); + ObjectNode plan = readProposedPlanWithRepair(project, run); + ProjectService.PlanView saved = projectService.saveDraftPlan(project.id(), plan, userId); + ObjectNode ask = objectMapper.createObjectNode(); + ask.put("kind", "planning"); + ask.put("interruptId", "plan-" + saved.id()); + ask.put("title", "确认建设规划"); + ask.put("description", "确认后 Agent 将自主完成申报书编写与评审"); + ask.set("plan", plan); + ask.put("planId", saved.id().toString()); + finishWaiting(project.id(), run.id(), ask); + } catch (Exception exception) { + failUnlessInterrupted(run, exception); + } + } + + /** + * 读取建议规划;结构无效时把原因反馈给同一线程继续修复。 + * + * @param project 当前项目 + * @param run 当前 Run + * @return 有效建设规划 + * @throws IOException 文件无法读取时抛出 + */ + private ObjectNode readProposedPlanWithRepair(ProjectService.ProjectView project, RunView run) + throws IOException { + int repairRound = 0; + while (true) { + try { + return outputService.readProposedPlan(project.id()); + } catch (ApiException | IOException exception) { + runStore.ensureRunning(run.id()); + repairRound++; + log.warn("Agent 未生成有效建设规划,继续同一线程修复,runId={},round={}", + run.id(), repairRound, exception); + streamAgent(project, run, """ + 建设规划结构化产物校验失败:%s + 请使用简体中文,复用当前上下文,立即修复 work/plans/proposed-plan.json 并调用 read_file 复核。 + 必须包含 coreDirection、collaborationDirection、factoryName、planningYears(1-10 整数)、 + investmentRange、applicationLevel、scenarios(非空数组)、aiScenarioCount 和 assumptions。 + 完成有效文件后再结束本轮。 + """.formatted(exception.getMessage())); + } + } + } + + private void executeWritingRun( + ProjectService.ProjectView project, + ProjectService.PlanView plan, + RunView run, + boolean resuming) { + try { + eventService.append(project.id(), run.id(), "RUN_STARTED", Map.of( + "threadId", project.threadId(), "runId", run.id(), "phase", "WRITING")); + String prompt = """ + 建设规划已确认。企业:%s,申报等级:%s。 + 确认规划 JSON:%s + 请自主完成完整申报书:调用分章编写、总结、评审和 docx Skill;按需调用百炼知识库。 + 你拥有当前项目工作区的读、写和 shell 能力。最终文件必须保存到 artifacts/,扩展名为 .docx。 + 任何有企业材料可核对的内容必须据实;缺少企业事实的内容允许结合知识库形成合理方案,且在 Word 原生批注中标明待确认。 + 正文目标为 1 万至 2 万汉字。关键现状未知可以待确认;建设场景、技术路线、实施阶段、建议 KPI 和保障机制等未来规划必须结合材料、知识库和 Skill 充分展开,不能以待确认占位代替可合理形成的方案。 + 最终事实审计必须逐句检查:未知企业现状使用“需确认是否……”或“待企业提供……”等非断言句式,严禁先写肯定事实再附待确认批注;企业承诺必须写为待签署或待提供。 + 每个 Word 原生批注 ID 只能锚定一处,commentRangeStart、commentRangeEnd、commentReference 必须各出现且仅出现一次;同一问题在多处引用时必须复制批注正文并分配新的唯一 ID。 + 即使 artifacts/ 已有旧稿,也必须为本轮重新生成并覆盖 DOCX,再执行结构、一致性和事实边界校验。 + 请保持章节口径一致,完成评审后再交付。 + 最终回复只说明申报书完成情况和用户需要关注的确认事项,不汇报内部文件、工具、命令、落盘或校验过程。 + """.formatted(project.companyName(), project.applicationLevel(), plan.plan().toString()); + streamAgent(project, run, recoveryPrompt(prompt, resuming)); + + JsonNode metadata = objectMapper.valueToTree(Map.of( + "planVersion", plan.version(), + "companyName", project.companyName(), + "review", "DOCX 已通过结构与一致性校验")); + publishAndComplete(project.id(), run, metadata); + } catch (Exception exception) { + failUnlessInterrupted(run, exception); + } + } + + private void streamAgent(ProjectService.ProjectView project, RunView run, String prompt) { + RunControl control = activeRuns.get(run.id()); + executionService.execute( + project, + run, + """ + 用户可见正文和执行说明默认使用简体中文;代码、命令、文件路径、标准原文和专有名词可保留原语言。 + + """ + prompt, + control == null ? reactor.core.publisher.Mono.never() : control.stopSignal.asMono(), + () -> runStore.ensureRunning(run.id()), + () -> runStore.isInterrupted(run.id())); + } + + /** + * 将运行切换为等待输入。 + * + * @param projectId 项目 ID + * @param runId Run ID + * @param interrupt Ask 内容 + */ + private void finishWaiting(UUID projectId, UUID runId, JsonNode interrupt) { + transactions.executeWithoutResult(status -> { + eventService.append(projectId, runId, "ASK_REQUESTED", interrupt); + int updated = jdbc.sql(""" + UPDATE app.agent_run + SET status = 'WAITING_INPUT', pending_interrupt = CAST(:interrupt AS jsonb), + ended_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE id = :id AND status = 'RUNNING' + """) + .param("interrupt", interrupt.toString()) + .param("id", runId) + .update(); + requireTerminalUpdate(updated); + eventService.append(projectId, runId, "RUN_FINISHED", Map.of("outcome", "INTERRUPT")); + }); + } + + /** + * 在当前事务成功提交后启动可中断的后台任务。 + * + * @param runId Run ID + * @param task 后台任务 + */ + private void afterCommit(UUID runId, Runnable task) { + RunControl control = new RunControl(); + activeRuns.put(runId, control); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + executor.submit(() -> { + try { + task.run(); + } finally { + activeRuns.remove(runId, control); + } + }); + } + + @Override + public void afterCompletion(int status) { + if (status != TransactionSynchronization.STATUS_COMMITTED) { + activeRuns.remove(runId, control); + } + } + }); + } + + /** + * 在当前事务成功提交后执行短操作。 + * + * @param action 提交后操作 + */ + private void onCommit(Runnable action) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + action.run(); + } + }); + } + + /** + * 为用户停止后的恢复 Run 增加上下文接续约束。 + * + * @param prompt 当前阶段提示词 + * @param resuming 是否恢复执行 + * @return 最终提示词 + */ + private String recoveryPrompt(String prompt, boolean resuming) { + if (!resuming) { + return prompt; + } + return """ + 这是用户停止后的继续运行。恢复同一 threadId 的会话状态,并先读取 MEMORY.md、work、references、artifacts。 + 复用已完成成果,从中断位置继续;不要重复已经完成的工具调用,先校验可能未完整写入的中间文件。 + + """ + prompt; + } + + /** + * 已中断的 Run 不再写入失败终态。 + * + * @param run 当前 Run + * @param exception 执行异常 + */ + private void failUnlessInterrupted(RunView run, Exception exception) { + if (exception instanceof AgentExecutionService.RunInterruptedException || runStore.isInterrupted(run.id())) { + log.info("Agent Run 已停止,runId={}", run.id()); + return; + } + fail(run, exception); + } + + /** + * 在一个事务中发布产物并标记运行正常完成。 + * + * @param projectId 项目 ID + * @param run 当前 Run + * @param metadata 产物元数据 + */ + private void publishAndComplete(UUID projectId, RunView run, JsonNode metadata) { + transactions.executeWithoutResult(status -> { + ArtifactService.ArtifactView artifact = artifactService.publishCandidate( + projectId, run.id(), run.startedAt().toInstant(), metadata); + eventService.append(projectId, run.id(), "ARTIFACT_PUBLISHED", artifact); + int updated = jdbc.sql(""" + UPDATE app.agent_run + SET status = 'COMPLETED', pending_interrupt = NULL, + ended_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE id = :id AND status = 'RUNNING' + """) + .param("id", run.id()) + .update(); + requireTerminalUpdate(updated); + projectService.updateStatus(projectId, "DELIVERED"); + eventService.append(projectId, run.id(), "RUN_FINISHED", Map.of("outcome", "SUCCESS")); + }); + } + + /** + * 原子标记运行失败并写入终止事件,已终止的 Run 不重复写事件。 + * + * @param run 当前 Run + * @param exception 执行异常 + */ + private void fail(RunView run, Exception exception) { + log.error("Agent Run 执行失败,runId={}", run.id(), exception); + String message = exception instanceof ApiException && exception.getMessage() != null + ? exception.getMessage() + : "Agent 执行失败,请稍后重试"; + try { + transactions.executeWithoutResult(status -> { + int updated = jdbc.sql(""" + UPDATE app.agent_run + SET status = 'FAILED', pending_interrupt = NULL, error_code = 'AGENT_RUN_FAILED', + error_message = :message, ended_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE id = :id AND status = 'RUNNING' + """) + .param("message", message) + .param("id", run.id()) + .update(); + if (updated == 1) { + eventService.append(run.projectId(), run.id(), "RUN_ERROR", Map.of( + "code", "AGENT_RUN_FAILED", "message", message)); + projectService.updateStatus(run.projectId(), "FAILED"); + } + }); + } catch (RuntimeException eventException) { + exception.addSuppressed(eventException); + log.error("Agent 失败事件持久化失败,runId={}", run.id(), eventException); + } + } + + /** + * 校验终态更新只命中当前运行中的 Run。 + * + * @param updated 更新行数 + */ + private void requireTerminalUpdate(int updated) { + if (updated != 1) { + throw new ApiException(HttpStatus.CONFLICT, "RUN_ALREADY_FINISHED", "当前任务已经结束"); + } + } + + /** + * Agent Run 视图。 + * + * @param id Run ID + * @param projectId 项目 ID + * @param triggerType 触发类型 + * @param status 运行状态 + * @param pendingInterrupt 待处理 Ask JSON + * @param errorMessage 失败信息 + * @param startedAt 开始时间 + * @param endedAt 结束时间 + */ + public record RunView( + UUID id, + UUID projectId, + String triggerType, + String status, + String pendingInterrupt, + String errorMessage, + OffsetDateTime startedAt, + OffsetDateTime endedAt) { + } + + /** + * 规划确认与编写启动的原子操作结果。 + * + * @param plan 已确认规划 + * @param run 编写 Run + */ + public record ConfirmPlanResult(ProjectService.PlanView plan, RunView run) { + } + + /** + * 保存活跃任务的流取消信号。 + */ + private static final class RunControl { + + private final Sinks.One stopSignal = Sinks.one(); + + /** + * 取消 Agent 流订阅,停止继续输出和后续工具调用。 + */ + private void cancel() { + stopSignal.tryEmitEmpty(); + } + } + +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunStore.java b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunStore.java new file mode 100644 index 0000000..4852eea --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/AgentRunStore.java @@ -0,0 +1,233 @@ +package cn.alphaline.smartfactory.agent; + +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.project.ProjectService; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.OffsetDateTime; +import java.util.UUID; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; + +/** + * 集中读写 Agent Run 持久化状态。 + */ +@Service +public class AgentRunStore { + + private final JdbcClient jdbc; + private final ObjectMapper objectMapper; + + /** + * 创建 Run 状态存储。 + * + * @param jdbc JDBC 客户端 + * @param objectMapper JSON 映射器 + */ + public AgentRunStore(JdbcClient jdbc, ObjectMapper objectMapper) { + this.jdbc = jdbc; + this.objectMapper = objectMapper; + } + + /** + * 创建无并发冲突的新 Run。 + * + * @param projectId 项目 ID + * @param triggerType 触发类型 + * @param parentRunId 父 Run ID + * @return 新 Run + */ + public AgentRunService.RunView create(UUID projectId, String triggerType, UUID parentRunId) { + Integer active = jdbc.sql(""" + SELECT count(*) FROM app.agent_run + WHERE project_id = :projectId AND status IN ('RUNNING', 'WAITING_INPUT') + """) + .param("projectId", projectId) + .query(Integer.class) + .single(); + if (active > 0) { + throw new ApiException(HttpStatus.CONFLICT, "RUN_ALREADY_ACTIVE", "项目已有正在执行或等待确认的任务"); + } + UUID id = UUID.randomUUID(); + UUID modelId = jdbc.sql("SELECT id FROM app.model_config WHERE is_default AND enabled") + .query(UUID.class) + .single(); + jdbc.sql(""" + INSERT INTO app.agent_run( + id, project_id, parent_run_id, model_config_id, trigger_type, status, trace_id) + VALUES (:id, :projectId, :parentRunId, :modelId, :triggerType, 'RUNNING', :traceId) + """) + .param("id", id) + .param("projectId", projectId) + .param("parentRunId", parentRunId) + .param("modelId", modelId) + .param("triggerType", triggerType) + .param("traceId", UUID.randomUUID().toString()) + .update(); + return require(id); + } + + /** + * 返回项目最近 Run。 + * + * @param projectId 项目 ID + * @return 最近 Run;不存在时为空 + */ + public AgentRunService.RunView latest(UUID projectId) { + return jdbc.sql(RUN_SELECT + " WHERE project_id = :projectId ORDER BY created_at DESC LIMIT 1") + .param("projectId", projectId) + .query(AgentRunStore::mapRun) + .optional() + .orElse(null); + } + + /** + * 获取指定 Run。 + * + * @param id Run ID + * @return Run + */ + public AgentRunService.RunView require(UUID id) { + return jdbc.sql(RUN_SELECT + " WHERE id = :id") + .param("id", id) + .query(AgentRunStore::mapRun) + .single(); + } + + /** + * 完成等待输入的 Run。 + * + * @param runId Run ID + */ + public void completeWaiting(UUID runId) { + int updated = jdbc.sql(""" + UPDATE app.agent_run + SET status = 'COMPLETED', pending_interrupt = NULL, updated_at = CURRENT_TIMESTAMP + WHERE id = :id AND status = 'WAITING_INPUT' + """) + .param("id", runId) + .update(); + if (updated != 1) { + throw new ApiException(HttpStatus.CONFLICT, "ASK_ALREADY_RESPONDED", "该确认已处理,请刷新页面"); + } + } + + /** + * 获取当前等待中的指定 Ask。 + * + * @param projectId 项目 ID + * @param kind Ask 类型 + * @return 等待中的 Run + */ + public AgentRunService.RunView requireWaiting(UUID projectId, String kind) { + AgentRunService.RunView run = latest(projectId); + if (run == null || !"WAITING_INPUT".equals(run.status()) || run.pendingInterrupt() == null) { + throw new ApiException(HttpStatus.CONFLICT, "ASK_NOT_WAITING", "当前没有等待确认的内容"); + } + try { + if (!kind.equals(objectMapper.readTree(run.pendingInterrupt()).path("kind").asText())) { + throw new ApiException(HttpStatus.CONFLICT, "ASK_TYPE_MISMATCH", "确认内容与当前阶段不一致"); + } + return run; + } catch (JsonProcessingException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "ASK_STATE_INVALID", "确认状态无法读取"); + } + } + + /** + * 确保 Run 仍处于运行状态。 + * + * @param runId Run ID + */ + public void ensureRunning(UUID runId) { + String status = jdbc.sql("SELECT status FROM app.agent_run WHERE id = :id") + .param("id", runId) + .query(String.class) + .single(); + if (!"RUNNING".equals(status)) { + throw new AgentExecutionService.RunInterruptedException(); + } + } + + /** + * 判断 Run 是否已由用户停止。 + * + * @param runId Run ID + * @return 是否已停止 + */ + public boolean isInterrupted(UUID runId) { + return jdbc.sql("SELECT status = 'INTERRUPTED' FROM app.agent_run WHERE id = :id") + .param("id", runId) + .query(Boolean.class) + .optional() + .orElse(false); + } + + /** + * 从持久化事件读取中断前阶段。 + * + * @param run 已中断 Run + * @param project 当前项目 + * @return 业务阶段 + */ + public String interruptedPhase(AgentRunService.RunView run, ProjectService.ProjectView project) { + return jdbc.sql(""" + SELECT payload ->> 'phase' FROM app.agent_event + WHERE run_id = :runId AND event_type = 'RUN_STARTED' + ORDER BY id DESC LIMIT 1 + """) + .param("runId", run.id()) + .query(String.class) + .optional() + .orElse(project.status()); + } + + /** + * 读取规划恢复所需的最近材料确认结果。 + * + * @param projectId 项目 ID + * @return 材料确认 JSON + */ + public JsonNode latestMaterialResponse(UUID projectId) { + return jdbc.sql(""" + SELECT payload::text FROM app.agent_event + WHERE project_id = :projectId AND event_type = 'ASK_RESPONDED' + AND jsonb_typeof(payload -> 'decisions') = 'array' + ORDER BY id DESC LIMIT 1 + """) + .param("projectId", projectId) + .query(String.class) + .optional() + .map(value -> { + try { + return objectMapper.readTree(value); + } catch (JsonProcessingException exception) { + throw new ApiException( + HttpStatus.INTERNAL_SERVER_ERROR, + "MATERIAL_RESPONSE_INVALID", + "材料确认记录无法读取"); + } + }) + .orElseGet(objectMapper::createObjectNode); + } + + private static AgentRunService.RunView mapRun(java.sql.ResultSet rs, int rowNum) + throws java.sql.SQLException { + return new AgentRunService.RunView( + rs.getObject("id", UUID.class), + rs.getObject("project_id", UUID.class), + rs.getString("trigger_type"), + rs.getString("status"), + rs.getString("pending_interrupt"), + rs.getString("error_message"), + rs.getObject("started_at", OffsetDateTime.class), + rs.getObject("ended_at", OffsetDateTime.class)); + } + + private static final String RUN_SELECT = """ + SELECT id, project_id, trigger_type, status, pending_interrupt, error_message, started_at, ended_at + FROM app.agent_run + """; +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/DocumentViewTool.java b/server/src/main/java/cn/alphaline/smartfactory/agent/DocumentViewTool.java new file mode 100644 index 0000000..0a25234 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/DocumentViewTool.java @@ -0,0 +1,169 @@ +package cn.alphaline.smartfactory.agent; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.message.Base64Source; +import io.agentscope.core.message.ContentBlock; +import io.agentscope.core.message.ImageBlock; +import io.agentscope.core.message.TextBlock; +import io.agentscope.core.message.ToolResultBlock; +import io.agentscope.core.tool.Tool; +import io.agentscope.core.tool.ToolParam; +import io.agentscope.harness.agent.HarnessAgent; +import io.agentscope.harness.agent.filesystem.AbstractFilesystem; +import io.agentscope.harness.agent.filesystem.model.ExecuteResponse; +import io.agentscope.harness.agent.filesystem.model.FileDownloadResponse; +import io.agentscope.harness.agent.filesystem.model.WriteResult; +import io.agentscope.harness.agent.filesystem.sandbox.SandboxBackedFilesystem; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * 在当前 Harness 沙箱内把指定文档视图渲染为多模态图片。 + */ +public final class DocumentViewTool { + + private static final int TOOL_TIMEOUT_SECONDS = 180; + + private final ObjectMapper objectMapper; + private volatile HarnessAgent harness; + + /** + * 创建文档视觉工具。 + * + * @param objectMapper JSON 映射器 + */ + public DocumentViewTool(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * 绑定拥有沙箱工作区的 Harness Agent。 + * + * @param harness 当前工具所属的 Harness Agent + */ + void bind(HarnessAgent harness) { + this.harness = harness; + } + + /** + * 渲染一个或多个文档页面、幻灯片、工作表范围或图片,并把图片返回给多模态模型。 + * + * @param views 查看请求;建议每次不超过 5 个,允许按任务需要分批调用 + * @param runtimeContext 当前运行上下文 + * @return 包含结构化结果和成功图片的工具观察 + */ + @Tool( + name = "document_view", + description = "按需查看 PDF/DOCX 页、PPTX 幻灯片、XLS/XLSX 工作表范围或图片。" + + "先使用文档 Skill 做结构化读取,只有内容缺失、扫描件或视觉布局重要时再调用。" + + "views 支持多个请求,建议每次最多 5 个;单个失败不影响其他结果。", + readOnly = true) + public ToolResultBlock view( + @ToolParam( + name = "views", + description = "查看请求数组。path 为工作区相对路径;PDF/DOCX/PPTX 可给 page," + + "XLS/XLSX 可给 sheet 和 range;可选 dpi 72-220、format 为 png/jpeg。") + List views, + RuntimeContext runtimeContext) { + if (views == null || views.isEmpty()) { + return ToolResultBlock.text("document_view 执行失败:views 至少包含一个查看请求"); + } + HarnessAgent activeHarness = harness; + if (activeHarness == null) { + return ToolResultBlock.text("document_view 执行失败:当前 Agent 没有 Harness 工作区"); + } + AbstractFilesystem filesystem = activeHarness.getWorkspaceManager().getFilesystem(); + if (!(filesystem instanceof SandboxBackedFilesystem sandbox)) { + return ToolResultBlock.text("document_view 执行失败:当前工作区不支持文档渲染"); + } + + String directory = "work/tmp/document-view/" + UUID.randomUUID(); + String requestPath = directory + "/request.json"; + String resultPath = directory + "/result.json"; + try { + WriteResult write = filesystem.write( + runtimeContext, + requestPath, + objectMapper.writeValueAsString(Map.of("views", views))); + if (!write.isSuccess()) { + return ToolResultBlock.text("document_view 执行失败:" + write.error()); + } + ExecuteResponse execution = sandbox.execute( + runtimeContext, + "python /opt/agent-runtime/document_view.py " + requestPath + " " + resultPath, + TOOL_TIMEOUT_SECONDS); + FileDownloadResponse downloaded = filesystem.downloadFiles(runtimeContext, List.of(resultPath)).getFirst(); + if (!downloaded.isSuccess()) { + return ToolResultBlock.text("document_view 执行失败:" + + safeError(execution.output(), downloaded.error())); + } + + JsonNode result = objectMapper.readTree(new String(downloaded.content(), StandardCharsets.UTF_8)); + List output = new ArrayList<>(); + output.add(TextBlock.builder() + .text("document_view_result=" + objectMapper.writeValueAsString(result)) + .build()); + List> metadata = new ArrayList<>(); + for (JsonNode image : result.path("images")) { + String path = image.path("path").asText(); + FileDownloadResponse imageFile = filesystem.downloadFiles(runtimeContext, List.of(path)).getFirst(); + if (!imageFile.isSuccess()) { + continue; + } + output.add(ImageBlock.builder() + .source(Base64Source.builder() + .mediaType(image.path("mediaType").asText("image/png")) + .data(Base64.getEncoder().encodeToString(imageFile.content())) + .build()) + .build()); + metadata.add(objectMapper.convertValue(image, new TypeReference>() { })); + } + return ToolResultBlock.of(output, Map.of("images", metadata)); + } catch (Exception exception) { + return ToolResultBlock.text("document_view 执行失败:" + safeError(exception.getMessage(), null)); + } + } + + /** + * 选择并限制返回给 Agent 的诊断信息。 + * + * @param primary 首选错误信息 + * @param fallback 备用错误信息 + * @return 有界错误文本 + */ + private String safeError(String primary, String fallback) { + String value = primary == null || primary.isBlank() ? fallback : primary; + if (value == null || value.isBlank()) { + return "未返回可诊断信息,请缩小查看范围后重试"; + } + value = value.strip(); + return value.length() > 600 ? value.substring(value.length() - 600) : value; + } + + /** + * 单个文档查看参数。 + * + * @param path 工作区相对路径 + * @param page 一基页码或幻灯片编号 + * @param sheet 工作表名称 + * @param range Excel A1 范围 + * @param dpi 渲染 DPI + * @param format png 或 jpeg + */ + public record ViewRequest( + @ToolParam(name = "path", description = "工作区相对路径") String path, + @ToolParam(name = "page", required = false, description = "一基页码或幻灯片编号") Integer page, + @ToolParam(name = "sheet", required = false, description = "Excel 工作表名称") String sheet, + @ToolParam(name = "range", required = false, description = "Excel A1 范围,例如 A1:H30") String range, + @ToolParam(name = "dpi", required = false, description = "渲染 DPI,建议 120-180") Integer dpi, + @ToolParam(name = "format", required = false, description = "png 或 jpeg") String format) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/PagedReadFileTool.java b/server/src/main/java/cn/alphaline/smartfactory/agent/PagedReadFileTool.java new file mode 100644 index 0000000..5869ae3 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/PagedReadFileTool.java @@ -0,0 +1,191 @@ +package cn.alphaline.smartfactory.agent; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.tool.Tool; +import io.agentscope.core.tool.ToolParam; +import io.agentscope.harness.agent.filesystem.AbstractFilesystem; +import io.agentscope.harness.agent.filesystem.model.ExecuteResponse; +import io.agentscope.harness.agent.filesystem.model.ReadResult; +import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem; +import io.agentscope.harness.agent.workspace.WorkspacePathNormalizer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +/** + * 提供带明确续读位置的文件读取工具,避免沙箱输出上限造成静默截断。 + */ +final class PagedReadFileTool { + + static final int DEFAULT_PAGE_LINES = 400; + private static final int SAFE_PAGE_BYTES = 300 * 1024; + + private final AbstractFilesystem filesystem; + private final WorkspacePathNormalizer pathNormalizer; + private final ObjectMapper objectMapper; + + /** + * 创建分页读取工具。 + * + * @param filesystem AgentScope 文件系统 + * @param pathNormalizer 工作区路径归一化器 + * @param objectMapper JSON 映射器 + */ + PagedReadFileTool( + AbstractFilesystem filesystem, + WorkspacePathNormalizer pathNormalizer, + ObjectMapper objectMapper) { + this.filesystem = filesystem; + this.pathNormalizer = pathNormalizer; + this.objectMapper = objectMapper; + } + + /** + * 按行读取文件;内容未读完时返回下一页 offset。 + * + * @param runtimeContext Agent 运行上下文 + * @param path 文件路径 + * @param offset 起始行,基于零 + * @param limit 本页最多行数 + * @return 文件内容及必要的续读提示 + */ + @Tool( + name = "read_file", + readOnly = true, + description = + "Read UTF-8 file content by lines. When content remains, the result explicitly" + + " provides nextOffset for the next call.") + public String readFile( + RuntimeContext runtimeContext, + @ToolParam(name = "path", description = "File path to read") String path, + @ToolParam( + name = "offset", + description = "Start line (0-indexed). Default: 0", + required = false) + Integer offset, + @ToolParam( + name = "limit", + description = "Max lines to return. Default: 400", + required = false) + Integer limit) { + int start = offset == null ? 0 : offset; + int pageLines = limit == null || limit <= 0 ? DEFAULT_PAGE_LINES : limit; + if (start < 0) { + return "Error: offset 不能小于 0"; + } + String normalizedPath = pathNormalizer.normalize(path); + if (filesystem instanceof AbstractSandboxFilesystem sandbox) { + return readFromSandbox(sandbox, runtimeContext, normalizedPath, start, pageLines); + } + return readFromFilesystem(runtimeContext, normalizedPath, start, pageLines); + } + + private String readFromSandbox( + AbstractSandboxFilesystem sandbox, + RuntimeContext runtimeContext, + String path, + int offset, + int limit) { + String encodedPath = Base64.getEncoder().encodeToString(path.getBytes(StandardCharsets.UTF_8)); + String command = """ + python3 - <<'PY' + import base64, json + path = base64.b64decode('%s').decode('utf-8') + offset = %d + limit = %d + cap = %d + try: + with open(path, 'rb') as source: + text = source.read().decode('utf-8') + lines = text.splitlines() + start = min(offset, len(lines)) + selected = [] + size = 0 + line_too_long = False + for line in lines[start:start + limit]: + data = (line + '\\n').encode('utf-8') + if size + len(data) > cap: + line_too_long = not selected + break + selected.append(line) + size += len(data) + next_offset = start + len(selected) + meta = { + 'ok': True, + 'truncated': next_offset < len(lines), + 'nextOffset': next_offset, + 'returnedLines': len(selected), + 'lineTooLong': line_too_long + } + print(json.dumps(meta, ensure_ascii=False, separators=(',', ':'))) + print(base64.b64encode('\\n'.join(selected).encode('utf-8')).decode('ascii')) + except FileNotFoundError: + print(json.dumps({'ok': False, 'error': 'file_not_found'}, separators=(',', ':'))) + except UnicodeDecodeError: + print(json.dumps({'ok': False, 'error': 'not_utf8_text'}, separators=(',', ':'))) + except Exception as error: + print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False, separators=(',', ':'))) + PY + """.formatted(encodedPath, offset, limit, SAFE_PAGE_BYTES); + ExecuteResponse response = sandbox.execute(runtimeContext, command, null); + String output = response.output() == null ? "" : response.output(); + int split = output.indexOf('\n'); + String header = split < 0 ? output.strip() : output.substring(0, split).strip(); + try { + JsonNode meta = objectMapper.readTree(header); + if (!meta.path("ok").asBoolean()) { + return switch (meta.path("error").asText()) { + case "file_not_found" -> "Error: 文件不存在:" + path; + case "not_utf8_text" -> "Error: 文件不是 UTF-8 文本,请调用相应文档 Skill 或 document_view"; + default -> "Error: 读取文件失败:" + meta.path("error").asText("未知错误"); + }; + } + int nextOffset = meta.path("nextOffset").asInt(offset); + if (response.truncated()) { + return incompleteNotice(path, nextOffset, limit); + } + String encoded = split < 0 ? "" : output.substring(split + 1).strip(); + String content = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); + if (meta.path("lineTooLong").asBoolean()) { + return "Error: 当前行超过安全读取范围,请使用 execute_shell_command 分段读取该行;内容未被静默截断"; + } + return meta.path("truncated").asBoolean() + ? content + "\n\n" + incompleteNotice(path, nextOffset, limit) + : content; + } catch (Exception exception) { + return "Error: 无法解析文件读取结果,内容可能未读完,请缩小 limit 后重试"; + } + } + + private String readFromFilesystem( + RuntimeContext runtimeContext, String path, int offset, int limit) { + ReadResult result = filesystem.read(runtimeContext, path, offset, limit + 1); + if (!result.isSuccess()) { + return "Error: " + result.error(); + } + if (result.fileData() == null) { + return ""; + } + if (!"utf-8".equalsIgnoreCase(result.fileData().encoding())) { + return result.fileData().content(); + } + String[] lines = result.fileData().content().split("\\R", -1); + if (lines.length <= limit) { + return result.fileData().content(); + } + return String.join("\n", java.util.Arrays.copyOf(lines, limit)) + + "\n\n" + + incompleteNotice(path, offset + limit, limit); + } + + private String incompleteNotice(String path, int nextOffset, int limit) { + return "[系统提示:内容未读完。请继续调用 read_file(path=\"" + + path + + "\", offset=" + + nextOffset + + ", limit=" + + limit + + ")。]"; + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/agent/RunRecoveryService.java b/server/src/main/java/cn/alphaline/smartfactory/agent/RunRecoveryService.java new file mode 100644 index 0000000..4a4144f --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/agent/RunRecoveryService.java @@ -0,0 +1,44 @@ +package cn.alphaline.smartfactory.agent; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +/** + * 启动时终结因 JVM 中断而遗留的伪运行状态,并保留原业务阶段供继续执行。 + */ +@Component +@Order(0) +public class RunRecoveryService implements ApplicationRunner { + + private final JdbcClient jdbc; + + /** + * 创建恢复服务。 + * + * @param jdbc JDBC 客户端 + */ + public RunRecoveryService(JdbcClient jdbc) { + this.jdbc = jdbc; + } + + /** + * 将仍为 RUNNING 的旧 Run 标记为已中断。 + * + * @param args 启动参数 + */ + @Override + @Transactional + public void run(ApplicationArguments args) { + jdbc.sql(""" + UPDATE app.agent_run + SET status = 'INTERRUPTED', pending_interrupt = NULL, + error_code = 'PROCESS_RESTARTED', error_message = '服务重启,运行已中断', + ended_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE status = 'RUNNING' + """).update(); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactController.java b/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactController.java new file mode 100644 index 0000000..394877d --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactController.java @@ -0,0 +1,59 @@ +package cn.alphaline.smartfactory.artifact; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 提供项目产物列表与下载接口。 + */ +@RestController +@RequestMapping("/api") +public class ArtifactController { + + private final ArtifactService artifactService; + + /** + * 创建产物控制器。 + * + * @param artifactService 产物服务 + */ + public ArtifactController(ArtifactService artifactService) { + this.artifactService = artifactService; + } + + /** + * 列出项目产物。 + * + * @param projectId 项目 ID + * @return 产物列表 + */ + @GetMapping("/projects/{projectId}/artifacts") + public List list(@PathVariable UUID projectId) { + return artifactService.list(projectId); + } + + /** + * 下载产物。 + * + * @param artifactId 产物 ID + * @return 文件响应 + */ + @GetMapping("/artifacts/{artifactId}/download") + public ResponseEntity download(@PathVariable UUID artifactId) { + ArtifactService.Download download = artifactService.download(artifactId); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(download.mimeType())) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename*=UTF-8''" + URLEncoder.encode(download.name(), StandardCharsets.UTF_8)) + .body(download.resource()); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactService.java b/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactService.java new file mode 100644 index 0000000..b8ef34b --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/artifact/ArtifactService.java @@ -0,0 +1,307 @@ +package cn.alphaline.smartfactory.artifact; + +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.project.ProjectFileService; +import com.fasterxml.jackson.databind.JsonNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; + +/** + * 校验、登记和下载 Agent 最终产物。 + */ +@Service +public class ArtifactService { + + private final JdbcClient jdbc; + private final ProjectFileService fileService; + private final DocxValidator docxValidator; + + /** + * 创建产物服务。 + * + * @param jdbc JDBC 客户端 + * @param fileService 项目文件服务 + * @param docxValidator DOCX 校验器 + */ + public ArtifactService(JdbcClient jdbc, ProjectFileService fileService, DocxValidator docxValidator) { + this.jdbc = jdbc; + this.fileService = fileService; + this.docxValidator = docxValidator; + } + + /** + * 校验本轮沙箱候选 DOCX,原子复制到正式目录并登记产物。 + * + * @param projectId 项目 ID + * @param runId Run ID + * @param runStartedAt Run 开始时间 + * @param metadata 业务元数据 + * @return 已发布产物 + */ + public ArtifactView publishCandidate( + UUID projectId, + UUID runId, + Instant runStartedAt, + JsonNode metadata) { + Path candidates = fileService.safeProjectPath(projectId, "work/candidates"); + Path candidate = newestDocx(candidates, runStartedAt); + DocxValidator.ValidationResult validation = docxValidator.validate(candidate); + Path target = fileService.safeProjectPath(projectId, "artifacts/" + candidate.getFileName()); + Path temporary = target.resolveSibling(target.getFileName() + ".publishing"); + try { + Files.copy(candidate, temporary, StandardCopyOption.REPLACE_EXISTING); + docxValidator.validate(temporary); + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException exception) { + try { + Files.deleteIfExists(temporary); + } catch (IOException cleanupException) { + exception.addSuppressed(cleanupException); + } + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "ARTIFACT_COPY_FAILED", "申报书发布失败"); + } + com.fasterxml.jackson.databind.node.ObjectNode enriched = metadata.isObject() + ? ((com.fasterxml.jackson.databind.node.ObjectNode) metadata).deepCopy() + : com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); + enriched.put("docxValidated", true); + enriched.put("docxEntries", validation.entryCount()); + enriched.put("commentCount", validation.commentCount()); + return publish( + projectId, + runId, + "DOCX", + target.getFileName().toString(), + "artifacts/" + target.getFileName(), + enriched); + } + + /** + * 发布工作区中的 DOCX 产物。 + * + * @param projectId 项目 ID + * @param runId Run ID + * @param kind 产物类型 + * @param name 文件名 + * @param relativePath 项目相对路径 + * @param metadata 业务摘要 + * @return 产物元数据 + */ + public ArtifactView publish( + UUID projectId, + UUID runId, + String kind, + String name, + String relativePath, + JsonNode metadata) { + Path path = fileService.safeProjectPath(projectId, relativePath); + if (!relativePath.startsWith("artifacts/") || !Files.isRegularFile(path)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "ARTIFACT_INVALID", "产物文件不存在或不在发布目录"); + } + try { + long size = Files.size(path); + if (size <= 0) { + throw new ApiException(HttpStatus.BAD_REQUEST, "ARTIFACT_EMPTY", "产物文件为空"); + } + String hash = sha256(path); + UUID id = jdbc.sql(""" + INSERT INTO app.artifact( + id, project_id, run_id, kind, name, relative_path, mime_type, + size_bytes, sha256, metadata_json) + VALUES (:id, :projectId, :runId, :kind, :name, :path, + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + :size, :sha256, CAST(:metadata AS jsonb)) + ON CONFLICT (project_id, relative_path) DO UPDATE SET + run_id = EXCLUDED.run_id, + kind = EXCLUDED.kind, + name = EXCLUDED.name, + mime_type = EXCLUDED.mime_type, + size_bytes = EXCLUDED.size_bytes, + sha256 = EXCLUDED.sha256, + metadata_json = EXCLUDED.metadata_json, + published_at = CURRENT_TIMESTAMP + RETURNING id + """) + .param("id", UUID.randomUUID()) + .param("projectId", projectId) + .param("runId", runId) + .param("kind", kind) + .param("name", name) + .param("path", relativePath) + .param("size", size) + .param("sha256", hash) + .param("metadata", metadata.toString()) + .query(UUID.class) + .single(); + return require(id); + } catch (IOException | NoSuchAlgorithmException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "ARTIFACT_PUBLISH_FAILED", "产物校验失败"); + } + } + + private Path newestDocx(Path directory, Instant runStartedAt) { + try (java.util.stream.Stream paths = Files.list(directory)) { + return paths + .filter(path -> path.getFileName().toString().toLowerCase(java.util.Locale.ROOT).endsWith(".docx")) + .filter(path -> path.toFile().lastModified() >= runStartedAt.toEpochMilli()) + .max(java.util.Comparator.comparingLong(path -> path.toFile().lastModified())) + .orElseThrow(() -> new ApiException( + HttpStatus.UNPROCESSABLE_ENTITY, + "DOCX_NOT_GENERATED", + "Agent 未生成本轮 DOCX")); + } catch (IOException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "ARTIFACT_SCAN_FAILED", "申报书候选目录无法读取"); + } + } + + /** + * 列出项目产物。 + * + * @param projectId 项目 ID + * @return 按发布时间倒序的产物 + */ + public List list(UUID projectId) { + return jdbc.sql(ARTIFACT_SELECT + " WHERE project_id = :projectId ORDER BY published_at DESC") + .param("projectId", projectId) + .query(ArtifactService::mapArtifact) + .list(); + } + + /** + * 获取产物下载资源。 + * + * @param artifactId 产物 ID + * @return 下载信息 + */ + public Download download(UUID artifactId) { + StoredArtifact artifact = jdbc.sql(""" + SELECT project_id, name, relative_path, mime_type, size_bytes, sha256 + FROM app.artifact WHERE id = :id + """) + .param("id", artifactId) + .query((rs, rowNum) -> new StoredArtifact( + rs.getObject("project_id", UUID.class), + rs.getString("name"), + rs.getString("relative_path"), + rs.getString("mime_type"), + rs.getLong("size_bytes"), + rs.getString("sha256"))) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "ARTIFACT_NOT_FOUND", "产物不存在")); + try { + Path path = fileService.safeProjectPath(artifact.projectId(), artifact.relativePath()); + Resource resource = new UrlResource(path.toUri()); + if (!resource.exists()) { + throw new ApiException(HttpStatus.NOT_FOUND, "ARTIFACT_FILE_NOT_FOUND", "产物文件不存在"); + } + if (Files.size(path) != artifact.sizeBytes() || !sha256(path).equals(artifact.sha256())) { + throw new ApiException(HttpStatus.CONFLICT, "ARTIFACT_INTEGRITY_FAILED", "产物完整性校验失败,请重新生成"); + } + return new Download(artifact.name(), artifact.mimeType(), resource); + } catch (java.net.MalformedURLException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "ARTIFACT_PATH_INVALID", "产物路径无效"); + } catch (IOException | NoSuchAlgorithmException exception) { + throw new ApiException(HttpStatus.CONFLICT, "ARTIFACT_INTEGRITY_FAILED", "产物完整性校验失败,请重新生成"); + } + } + + /** + * 计算文件 SHA-256。 + * + * @param path 文件路径 + * @return 小写十六进制哈希 + * @throws IOException 文件读取失败时抛出 + * @throws NoSuchAlgorithmException 运行环境不支持 SHA-256 时抛出 + */ + private String sha256(Path path) throws IOException, NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (InputStream input = Files.newInputStream(path)) { + byte[] buffer = new byte[8192]; + for (int read; (read = input.read(buffer)) >= 0;) { + digest.update(buffer, 0, read); + } + } + return HexFormat.of().formatHex(digest.digest()); + } + + private ArtifactView require(UUID id) { + return jdbc.sql(ARTIFACT_SELECT + " WHERE id = :id") + .param("id", id) + .query(ArtifactService::mapArtifact) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "ARTIFACT_NOT_FOUND", "产物不存在")); + } + + private static ArtifactView mapArtifact(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + return new ArtifactView( + rs.getObject("id", UUID.class), + rs.getObject("project_id", UUID.class), + rs.getObject("run_id", UUID.class), + rs.getString("kind"), + rs.getString("name"), + rs.getLong("size_bytes"), + rs.getString("metadata_json"), + rs.getObject("published_at", OffsetDateTime.class)); + } + + private static final String ARTIFACT_SELECT = """ + SELECT id, project_id, run_id, kind, name, size_bytes, metadata_json, published_at + FROM app.artifact + """; + + /** + * 产物元数据。 + * + * @param id 产物 ID + * @param projectId 项目 ID + * @param runId 生成 Run + * @param kind 类型 + * @param name 文件名 + * @param sizeBytes 文件大小 + * @param metadataJson 业务摘要 JSON + * @param publishedAt 发布时间 + */ + public record ArtifactView( + UUID id, + UUID projectId, + UUID runId, + String kind, + String name, + long sizeBytes, + String metadataJson, + OffsetDateTime publishedAt) { + } + + /** + * 下载结果。 + * + * @param name 下载文件名 + * @param mimeType MIME 类型 + * @param resource 文件资源 + */ + public record Download(String name, String mimeType, Resource resource) { + } + + private record StoredArtifact( + UUID projectId, + String name, + String relativePath, + String mimeType, + long sizeBytes, + String sha256) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/artifact/DocxValidator.java b/server/src/main/java/cn/alphaline/smartfactory/artifact/DocxValidator.java new file mode 100644 index 0000000..fd60dd5 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/artifact/DocxValidator.java @@ -0,0 +1,194 @@ +package cn.alphaline.smartfactory.artifact; + +import cn.alphaline.smartfactory.common.ApiException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * 使用 JDK 标准库校验 DOCX 容器、核心 OOXML 和原生批注引用。 + */ +@Component +public class DocxValidator { + + private static final Set REQUIRED_ENTRIES = Set.of( + "[Content_Types].xml", "_rels/.rels", "word/document.xml"); + private static final int MAX_ENTRIES = 10_000; + private static final long MAX_UNCOMPRESSED_BYTES = 512L * 1024 * 1024; + + /** + * 校验 DOCX 文件可以被 Word 作为完整 OOXML 文档读取。 + * + * @param path DOCX 文件 + * @return 校验摘要 + * @throws ApiException 文件损坏、结构缺失或批注引用异常时抛出 + */ + public ValidationResult validate(Path path) { + if (!Files.isRegularFile(path)) { + throw invalid("DOCX 文件不存在"); + } + try (ZipFile zip = new ZipFile(path.toFile())) { + Set names = new HashSet<>(); + long uncompressed = 0; + var entries = zip.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + String name = entry.getName(); + if (name.startsWith("/") || name.contains("../") || !names.add(name)) { + throw invalid("DOCX 包含非法或重复路径"); + } + if (names.size() > MAX_ENTRIES) { + throw invalid("DOCX 文件数量超过限制"); + } + if (entry.getSize() > 0) { + uncompressed = Math.addExact(uncompressed, entry.getSize()); + if (uncompressed > MAX_UNCOMPRESSED_BYTES) { + throw invalid("DOCX 解压后大小超过限制"); + } + } + } + if (!names.containsAll(REQUIRED_ENTRIES)) { + throw invalid("DOCX 缺少必要的 Word 文档结构"); + } + + Document document = parse(zip, "word/document.xml"); + if (!"document".equals(document.getDocumentElement().getLocalName()) + || document.getElementsByTagNameNS("*", "body").getLength() != 1 + || document.getElementsByTagNameNS("*", "t").getLength() == 0) { + throw invalid("DOCX 正文结构为空或无效"); + } + int comments = validateComments(zip, names, document); + return new ValidationResult(Files.size(path), names.size(), comments); + } catch (ApiException exception) { + throw exception; + } catch (ArithmeticException | IOException exception) { + throw invalid("DOCX 容器损坏或无法读取"); + } + } + + private int validateComments(ZipFile zip, Set names, Document document) throws IOException { + Map references = idCounts(document, "commentReference"); + Map starts = idCounts(document, "commentRangeStart"); + Map ends = idCounts(document, "commentRangeEnd"); + Set referenced = new HashSet<>(references.keySet()); + referenced.addAll(starts.keySet()); + referenced.addAll(ends.keySet()); + if (!names.contains("word/comments.xml")) { + if (!referenced.isEmpty()) { + throw invalid("DOCX 正文引用了不存在的批注"); + } + return 0; + } + + Document comments = parse(zip, "word/comments.xml"); + Set declared = new HashSet<>(); + NodeList nodes = comments.getElementsByTagNameNS("*", "comment"); + for (int index = 0; index < nodes.getLength(); index++) { + String id = attributeByLocalName((Element) nodes.item(index), "id"); + if (id.isBlank() || !declared.add(id)) { + throw invalid("DOCX 包含重复或无编号批注"); + } + } + if (declared.isEmpty() || !declared.equals(referenced)) { + throw invalid("DOCX 批注与正文锚点不一致"); + } + for (String id : declared) { + if (references.getOrDefault(id, 0) != 1 + || starts.getOrDefault(id, 0) != 1 + || ends.getOrDefault(id, 0) != 1) { + throw invalid("DOCX 批注锚点重复或不完整"); + } + } + if (!names.contains("word/_rels/document.xml.rels")) { + throw invalid("DOCX 批注缺少关系定义"); + } + Document relationships = parse(zip, "word/_rels/document.xml.rels"); + boolean linked = false; + NodeList relations = relationships.getElementsByTagNameNS("*", "Relationship"); + for (int index = 0; index < relations.getLength(); index++) { + Element relation = (Element) relations.item(index); + if ("comments.xml".equals(relation.getAttribute("Target"))) { + linked = true; + break; + } + } + if (!linked) { + throw invalid("DOCX 批注关系未连接到正文"); + } + return declared.size(); + } + + private Map idCounts(Document document, String localName) { + Map values = new HashMap<>(); + NodeList nodes = document.getElementsByTagNameNS("*", localName); + for (int index = 0; index < nodes.getLength(); index++) { + String id = attributeByLocalName((Element) nodes.item(index), "id"); + if (!id.isBlank()) { + values.merge(id, 1, Integer::sum); + } + } + return values; + } + + private String attributeByLocalName(Element element, String localName) { + for (int index = 0; index < element.getAttributes().getLength(); index++) { + Node attribute = element.getAttributes().item(index); + if (localName.equals(attribute.getLocalName()) || localName.equals(attribute.getNodeName())) { + return attribute.getNodeValue(); + } + } + return ""; + } + + private Document parse(ZipFile zip, String name) throws IOException { + ZipEntry entry = zip.getEntry(name); + if (entry == null) { + throw invalid("DOCX 缺少必要 XML:" + name); + } + try (InputStream input = zip.getInputStream(entry)) { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setXIncludeAware(false); + factory.setExpandEntityReferences(false); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + return factory.newDocumentBuilder().parse(input); + } catch (ApiException exception) { + throw exception; + } catch (Exception exception) { + throw invalid("DOCX XML 无法解析:" + name); + } + } + + private ApiException invalid(String message) { + return new ApiException(HttpStatus.UNPROCESSABLE_ENTITY, "DOCX_INVALID", message); + } + + /** + * DOCX 校验摘要。 + * + * @param sizeBytes 文件大小 + * @param entryCount ZIP 条目数 + * @param commentCount 原生批注数 + */ + public record ValidationResult(long sizeBytes, int entryCount, int commentCount) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/auth/AuthController.java b/server/src/main/java/cn/alphaline/smartfactory/auth/AuthController.java new file mode 100644 index 0000000..59edd2a --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/auth/AuthController.java @@ -0,0 +1,104 @@ +package cn.alphaline.smartfactory.auth; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import java.security.Principal; +import java.util.Map; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * 管理登录状态和 CSRF Token。 + */ +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private final AuthenticationManager authenticationManager; + private final HttpSessionSecurityContextRepository contextRepository = new HttpSessionSecurityContextRepository(); + + /** + * 创建认证控制器。 + * + * @param authenticationManager 认证管理器 + */ + public AuthController(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + /** + * 返回并初始化 CSRF Token。 + * + * @param token 当前请求 Token + * @return Token 数据 + */ + @GetMapping("/csrf") + public Map csrf(CsrfToken token) { + return Map.of("token", token.getToken(), "headerName", token.getHeaderName()); + } + + /** + * 使用用户名和密码创建 Session。 + * + * @param request 登录请求 + * @param servletRequest HTTP 请求 + * @param servletResponse HTTP 响应 + * @return 当前用户摘要 + */ + @PostMapping("/login") + public MeResponse login( + @Valid @RequestBody LoginRequest request, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) { + Authentication authentication = authenticationManager.authenticate( + UsernamePasswordAuthenticationToken.unauthenticated(request.username(), request.password())); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + contextRepository.saveContext(context, servletRequest, servletResponse); + return new MeResponse(authentication.getName(), "管理员"); + } + + /** + * 返回当前登录账户。 + * + * @param principal 当前身份 + * @return 当前用户摘要 + */ + @GetMapping("/me") + public MeResponse me(Principal principal) { + return new MeResponse(principal.getName(), "管理员"); + } + + /** + * 登录请求。 + * + * @param username 登录名 + * @param password 密码 + */ + public record LoginRequest(@NotBlank String username, @NotBlank String password) { + } + + /** + * 当前用户摘要。 + * + * @param username 登录名 + * @param displayName 显示名称 + */ + public record MeResponse(String username, String displayName) { + } + +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/auth/UserService.java b/server/src/main/java/cn/alphaline/smartfactory/auth/UserService.java new file mode 100644 index 0000000..a0edff8 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/auth/UserService.java @@ -0,0 +1,97 @@ +package cn.alphaline.smartfactory.auth; + +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.config.AppProperties; +import java.util.UUID; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.core.annotation.Order; + +/** + * 管理单管理员账户和当前用户标识。 + */ +@Service +@Order(1) +public class UserService implements UserDetailsService, ApplicationRunner { + + private final JdbcClient jdbc; + private final PasswordEncoder passwordEncoder; + private final AppProperties properties; + + /** + * 创建用户服务。 + * + * @param jdbc JDBC 客户端 + * @param passwordEncoder 密码编码器 + * @param properties 应用配置 + */ + public UserService(JdbcClient jdbc, PasswordEncoder passwordEncoder, AppProperties properties) { + this.jdbc = jdbc; + this.passwordEncoder = passwordEncoder; + this.properties = properties; + } + + /** + * 初始化本地管理员账户。 + * + * @param args 启动参数 + */ + @Override + public void run(ApplicationArguments args) { + Integer count = jdbc.sql("SELECT count(*) FROM app.app_user").query(Integer.class).single(); + if (count == 0) { + jdbc.sql(""" + INSERT INTO app.app_user(id, username, password_hash, display_name) + VALUES (:id, :username, :password, :displayName) + """) + .param("id", UUID.randomUUID()) + .param("username", properties.adminUsername()) + .param("password", passwordEncoder.encode(properties.adminPassword())) + .param("displayName", "管理员") + .update(); + } + } + + /** + * 加载 Spring Security 用户。 + * + * @param username 登录名 + * @return 用户详情 + * @throws UsernameNotFoundException 用户不存在或被禁用时抛出 + */ + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return jdbc.sql("SELECT username, password_hash, enabled FROM app.app_user WHERE username = :username") + .param("username", username) + .query((rs, rowNum) -> User.withUsername(rs.getString("username")) + .password(rs.getString("password_hash")) + .roles("ADMIN") + .disabled(!rs.getBoolean("enabled")) + .build()) + .optional() + .orElseThrow(() -> new UsernameNotFoundException("账户不存在")); + } + + /** + * 获取指定登录名的用户 ID。 + * + * @param username 登录名 + * @return 用户 UUID + * @throws ApiException 用户不存在时抛出 + */ + public UUID requireUserId(String username) { + return jdbc.sql("SELECT id FROM app.app_user WHERE username = :username") + .param("username", username) + .query(UUID.class) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.UNAUTHORIZED, "USER_NOT_FOUND", "登录账户不存在")); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/common/ApiError.java b/server/src/main/java/cn/alphaline/smartfactory/common/ApiError.java new file mode 100644 index 0000000..3480598 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/common/ApiError.java @@ -0,0 +1,15 @@ +package cn.alphaline.smartfactory.common; + +import java.time.Instant; + +/** + * 统一接口错误响应。 + * + * @param code 稳定错误码 + * @param message 可理解错误信息 + * @param traceId 日志关联标识 + * @param timestamp 发生时间 + */ +public record ApiError(String code, String message, String traceId, Instant timestamp) { +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/common/ApiException.java b/server/src/main/java/cn/alphaline/smartfactory/common/ApiException.java new file mode 100644 index 0000000..b8ec4b4 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/common/ApiException.java @@ -0,0 +1,44 @@ +package cn.alphaline.smartfactory.common; + +import org.springframework.http.HttpStatus; + +/** + * 可安全返回给调用方的业务异常。 + */ +public class ApiException extends RuntimeException { + + private final HttpStatus status; + private final String code; + + /** + * 创建业务异常。 + * + * @param status HTTP 状态 + * @param code 稳定错误码 + * @param message 可操作错误说明 + */ + public ApiException(HttpStatus status, String code, String message) { + super(message); + this.status = status; + this.code = code; + } + + /** + * 返回 HTTP 状态。 + * + * @return HTTP 状态 + */ + public HttpStatus status() { + return status; + } + + /** + * 返回稳定错误码。 + * + * @return 错误码 + */ + public String code() { + return code; + } +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/common/GlobalExceptionHandler.java b/server/src/main/java/cn/alphaline/smartfactory/common/GlobalExceptionHandler.java new file mode 100644 index 0000000..69426a6 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/common/GlobalExceptionHandler.java @@ -0,0 +1,135 @@ +package cn.alphaline.smartfactory.common; + +import jakarta.validation.ConstraintViolationException; +import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; + +/** + * 将业务错误和未预期异常转换为明确的 HTTP 错误响应。 + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 处理已知业务异常。 + * + * @param exception 业务异常 + * @return 对应状态码的错误响应 + */ + @ExceptionHandler(ApiException.class) + public ResponseEntity handleApiException(ApiException exception) { + return ResponseEntity.status(exception.status()) + .body(error(exception.code(), exception.getMessage())); + } + + /** + * 处理输入校验失败。 + * + * @param exception 参数校验异常 + * @return 400 错误响应 + */ + @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class}) + public ResponseEntity handleValidation(Exception exception) { + String message = exception instanceof MethodArgumentNotValidException invalid + ? invalid.getBindingResult().getFieldErrors().stream() + .findFirst() + .map(error -> error.getField() + ":" + error.getDefaultMessage()) + .orElse("请求参数无效") + : exception.getMessage(); + return ResponseEntity.badRequest().body(error("VALIDATION_FAILED", message)); + } + + /** + * 将错误凭据统一映射为 401。 + * + * @param exception 认证异常 + * @return 401 错误响应 + */ + @ExceptionHandler(AuthenticationException.class) + public ResponseEntity handleAuthentication(AuthenticationException exception) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(error("AUTHENTICATION_FAILED", "用户名或密码错误")); + } + + /** + * 将权限或 CSRF 拒绝统一映射为 403。 + * + * @param exception 权限异常 + * @return 403 错误响应 + */ + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity handleAccessDenied(AccessDeniedException exception) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(error("ACCESS_DENIED", "当前请求无权执行")); + } + + /** + * 处理无法解析的请求体。 + * + * @param exception JSON 读取异常 + * @return 400 错误响应 + */ + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity handleUnreadable(HttpMessageNotReadableException exception) { + return ResponseEntity.badRequest().body(error("REQUEST_BODY_INVALID", "请求内容格式无效")); + } + + /** + * 处理数据库唯一性等并发冲突。 + * + * @param exception 数据约束异常 + * @return 409 错误响应 + */ + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity handleConflict(DataIntegrityViolationException exception) { + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(error("DATA_CONFLICT", "数据已发生变化,请刷新后重试")); + } + + /** + * 收敛流式响应中客户端主动断开产生的预期异常。 + * + * @param exception 已提交响应无法继续写入的异常 + */ + @ExceptionHandler(AsyncRequestNotUsableException.class) + public void handleClientDisconnect(AsyncRequestNotUsableException exception) { + log.debug("客户端已断开流式响应:{}", exception.getMessage()); + } + + /** + * 处理未预期异常并保留完整堆栈。 + * + * @param exception 未预期异常 + * @return 500 错误响应 + */ + @ExceptionHandler(Exception.class) + public ResponseEntity handleUnexpected(Exception exception) { + String traceId = traceId(); + log.error("未预期异常,traceId={}", traceId, exception); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ApiError("INTERNAL_ERROR", "服务处理失败,请稍后重试", traceId, java.time.Instant.now())); + } + + private ApiError error(String code, String message) { + return new ApiError(code, message, traceId(), java.time.Instant.now()); + } + + private String traceId() { + String value = MDC.get("traceId"); + return value == null || value.isBlank() ? UUID.randomUUID().toString() : value; + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/common/TraceIdFilter.java b/server/src/main/java/cn/alphaline/smartfactory/common/TraceIdFilter.java new file mode 100644 index 0000000..0e14796 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/common/TraceIdFilter.java @@ -0,0 +1,45 @@ +package cn.alphaline.smartfactory.common; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.UUID; +import org.slf4j.MDC; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +/** + * 为每个 HTTP 请求建立可回传、可检索的追踪编号。 + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class TraceIdFilter extends OncePerRequestFilter { + + /** + * 在请求处理期间写入 MDC,并在响应中返回追踪编号。 + * + * @param request HTTP 请求 + * @param response HTTP 响应 + * @param filterChain 后续过滤器链 + * @throws ServletException Servlet 处理失败 + * @throws IOException 网络读写失败 + */ + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + String traceId = UUID.randomUUID().toString(); + MDC.put("traceId", traceId); + response.setHeader("X-Trace-Id", traceId); + try { + filterChain.doFilter(request, response); + } finally { + MDC.remove("traceId"); + } + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/config/AppProperties.java b/server/src/main/java/cn/alphaline/smartfactory/config/AppProperties.java new file mode 100644 index 0000000..f76d20e --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/config/AppProperties.java @@ -0,0 +1,37 @@ +package cn.alphaline.smartfactory.config; + +import java.nio.file.Path; +import java.time.Duration; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * 应用自身的运行配置。 + * + * @param dataRoot 项目材料、工作区和产物根目录 + * @param deepseekKeyFile DeepSeek Key 文件 + * @param dashscopeKeyFile 百炼 Key 文件 + * @param masterKey 模型密钥加密主密钥 + * @param adminUsername 本地管理员用户名 + * @param adminPassword 本地管理员初始密码 + * @param modelBaseUrl 默认模型端点 + * @param modelId 默认模型标识 + * @param modelContextWindow 默认模型上下文窗口 + * @param sandboxImage Agent Docker 运行镜像 + * @param sandboxNetwork Agent Docker 网络 + * @param runTimeout 单次 Agent 运行超时 + */ +@ConfigurationProperties(prefix = "app") +public record AppProperties( + Path dataRoot, + Path deepseekKeyFile, + Path dashscopeKeyFile, + String masterKey, + String adminUsername, + String adminPassword, + String modelBaseUrl, + String modelId, + int modelContextWindow, + String sandboxImage, + String sandboxNetwork, + Duration runTimeout) { +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/config/InfraConfig.java b/server/src/main/java/cn/alphaline/smartfactory/config/InfraConfig.java new file mode 100644 index 0000000..73351f8 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/config/InfraConfig.java @@ -0,0 +1,36 @@ +package cn.alphaline.smartfactory.config; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.core.task.support.TaskExecutorAdapter; + +/** + * 进程内基础设施配置。 + */ +@Configuration +public class InfraConfig { + + /** + * 创建适合阻塞模型及文件调用的虚拟线程执行器。 + * + * @return 应用共享执行器 + */ + @Bean(destroyMethod = "close") + public ExecutorService applicationExecutor() { + return Executors.newVirtualThreadPerTaskExecutor(); + } + + /** + * 复用虚拟线程处理 Spring MVC 的异步响应。 + * + * @param applicationExecutor 应用共享执行器 + * @return MVC 异步执行器 + */ + @Bean + public AsyncTaskExecutor applicationTaskExecutor(ExecutorService applicationExecutor) { + return new TaskExecutorAdapter(applicationExecutor); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/config/SecurityConfig.java b/server/src/main/java/cn/alphaline/smartfactory/config/SecurityConfig.java new file mode 100644 index 0000000..8c27c87 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/config/SecurityConfig.java @@ -0,0 +1,96 @@ +package cn.alphaline.smartfactory.config; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiError; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.Instant; +import java.util.UUID; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; + +/** + * 单管理员 Cookie Session 安全配置。 + */ +@Configuration +public class SecurityConfig { + + /** + * 创建密码编码器。 + * + * @return BCrypt 编码器 + */ + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + /** + * 创建认证管理器。 + * + * @param configuration Spring Security 认证配置 + * @return 认证管理器 + * @throws Exception 配置解析失败时抛出 + */ + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { + return configuration.getAuthenticationManager(); + } + + /** + * 定义接口授权和 CSRF 规则。 + * + * @param http HTTP 安全构建器 + * @param userService 用户加载服务 + * @param objectMapper JSON 映射器 + * @return 安全过滤链 + * @throws Exception 安全规则构建失败时抛出 + */ + @Bean + public SecurityFilterChain securityFilterChain( + HttpSecurity http, + UserService userService, + ObjectMapper objectMapper) throws Exception { + CookieCsrfTokenRepository csrf = CookieCsrfTokenRepository.withHttpOnlyFalse(); + csrf.setCookiePath("/"); + return http + .userDetailsService(userService) + .csrf(configurer -> configurer + .csrfTokenRepository(csrf) + .ignoringRequestMatchers("/api/auth/login")) + .authorizeHttpRequests(registry -> registry + .requestMatchers("/api/auth/login", "/api/auth/csrf", "/", "/index.html", "/assets/**") + .permitAll() + .anyRequest().authenticated()) + .exceptionHandling(errors -> errors + .authenticationEntryPoint((request, response, exception) -> writeError( + response, objectMapper, 401, "AUTHENTICATION_REQUIRED", "请先登录")) + .accessDeniedHandler((request, response, exception) -> writeError( + response, objectMapper, 403, "ACCESS_DENIED", "当前请求无权执行"))) + .requestCache(cache -> cache.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .logout(logout -> logout.logoutUrl("/api/auth/logout").logoutSuccessHandler((request, response, authentication) -> response.setStatus(204))) + .build(); + } + + private void writeError( + jakarta.servlet.http.HttpServletResponse response, + ObjectMapper objectMapper, + int status, + String code, + String message) throws java.io.IOException { + response.setStatus(status); + response.setCharacterEncoding(java.nio.charset.StandardCharsets.UTF_8.name()); + response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_VALUE); + objectMapper.writeValue( + response.getOutputStream(), + new ApiError(code, message, UUID.randomUUID().toString(), Instant.now())); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/config/SkillRepositoryConfig.java b/server/src/main/java/cn/alphaline/smartfactory/config/SkillRepositoryConfig.java new file mode 100644 index 0000000..f991855 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/config/SkillRepositoryConfig.java @@ -0,0 +1,31 @@ +package cn.alphaline.smartfactory.config; + +import io.agentscope.core.skill.repository.postgresql.PostgresSkillRepository; +import javax.sql.DataSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * AgentScope PostgreSQL Skill Repository 配置。 + */ +@Configuration +public class SkillRepositoryConfig { + + /** + * 创建由 Flyway 管理表结构的 Skill 仓库。 + * + * @param dataSource 数据源 + * @return 可写 Skill 仓库 + */ + @Bean(destroyMethod = "close") + public PostgresSkillRepository postgresSkillRepository(DataSource dataSource) { + return PostgresSkillRepository.builder(dataSource) + .schemaName("agentscope") + .skillsTableName("agentscope_skills") + .resourcesTableName("agentscope_skill_resources") + .createIfNotExist(false) + .writeable(true) + .build(); + } +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/model/KeyCipher.java b/server/src/main/java/cn/alphaline/smartfactory/model/KeyCipher.java new file mode 100644 index 0000000..c1ff9a9 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/model/KeyCipher.java @@ -0,0 +1,84 @@ +package cn.alphaline.smartfactory.model; + +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.config.AppProperties; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Arrays; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +/** + * 使用 AES-GCM 加密数据库中的模型密钥。 + */ +@Component +public class KeyCipher { + + private static final int IV_LENGTH = 12; + private static final int TAG_LENGTH = 128; + + private final SecretKeySpec key; + private final SecureRandom random = new SecureRandom(); + + /** + * 创建密钥加密器。 + * + * @param properties 应用配置 + */ + public KeyCipher(AppProperties properties) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(properties.masterKey().getBytes(StandardCharsets.UTF_8)); + this.key = new SecretKeySpec(digest, "AES"); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("无法初始化密钥加密器", exception); + } + } + + /** + * 加密明文密钥。 + * + * @param plaintext 明文 + * @return IV 与密文组合字节 + */ + public byte[] encrypt(String plaintext) { + byte[] iv = new byte[IV_LENGTH]; + random.nextBytes(iv); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, iv)); + byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + return ByteBuffer.allocate(iv.length + ciphertext.length).put(iv).put(ciphertext).array(); + } catch (GeneralSecurityException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "KEY_ENCRYPT_FAILED", "模型密钥加密失败"); + } + } + + /** + * 解密数据库密钥。 + * + * @param encrypted IV 与密文组合字节 + * @return 明文密钥 + */ + public String decrypt(byte[] encrypted) { + if (encrypted == null || encrypted.length <= IV_LENGTH) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "KEY_MISSING", "模型密钥未配置"); + } + byte[] iv = Arrays.copyOfRange(encrypted, 0, IV_LENGTH); + byte[] ciphertext = Arrays.copyOfRange(encrypted, IV_LENGTH, encrypted.length); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, iv)); + return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8); + } catch (GeneralSecurityException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "KEY_DECRYPT_FAILED", "模型密钥解密失败"); + } + } +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/model/ModelController.java b/server/src/main/java/cn/alphaline/smartfactory/model/ModelController.java new file mode 100644 index 0000000..5cb8a96 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/model/ModelController.java @@ -0,0 +1,96 @@ +package cn.alphaline.smartfactory.model; + +import jakarta.validation.Valid; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * 提供模型配置与连接测试接口。 + */ +@RestController +@RequestMapping("/api/models") +public class ModelController { + + private final ModelService modelService; + + /** + * 创建模型控制器。 + * + * @param modelService 模型服务 + */ + public ModelController(ModelService modelService) { + this.modelService = modelService; + } + + /** + * 列出模型。 + * + * @return 模型列表 + */ + @GetMapping + public List list() { + return modelService.list(); + } + + /** + * 新增模型。 + * + * @param input 模型输入 + * @param principal 当前用户 + * @return 新模型 + */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public ModelService.ModelView create(@Valid @RequestBody ModelService.ModelInput input, Principal principal) { + return modelService.save(null, input, principal); + } + + /** + * 更新模型。 + * + * @param id 模型 ID + * @param input 模型输入 + * @param principal 当前用户 + * @return 更新后的模型 + */ + @PutMapping("/{id}") + public ModelService.ModelView update( + @PathVariable UUID id, + @Valid @RequestBody ModelService.ModelInput input, + Principal principal) { + return modelService.save(id, input, principal); + } + + /** + * 测试模型连接。 + * + * @param id 模型 ID + * @return 测试结果 + */ + @PostMapping("/{id}/test") + public ModelService.ConnectionResult test(@PathVariable UUID id) { + return modelService.test(id); + } + + /** + * 设置默认模型。 + * + * @param id 模型 ID + * @param principal 当前用户 + */ + @PostMapping("/{id}/default") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void setDefault(@PathVariable UUID id, Principal principal) { + modelService.setDefault(id, principal); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/model/ModelService.java b/server/src/main/java/cn/alphaline/smartfactory/model/ModelService.java new file mode 100644 index 0000000..d375519 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/model/ModelService.java @@ -0,0 +1,452 @@ +package cn.alphaline.smartfactory.model; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.config.AppProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.Principal; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import jakarta.validation.constraints.NotBlank; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 管理 OpenAI 兼容模型配置、密钥和连接测试。 + */ +@Service +@Order(2) +public class ModelService implements ApplicationRunner { + + private final JdbcClient jdbc; + private final UserService userService; + private final KeyCipher keyCipher; + private final AppProperties properties; + private final ObjectMapper objectMapper; + private final HttpClient httpClient; + + /** + * 创建模型服务。 + * + * @param jdbc JDBC 客户端 + * @param userService 用户服务 + * @param keyCipher 密钥加密器 + * @param properties 应用配置 + * @param objectMapper JSON 映射器 + */ + public ModelService( + JdbcClient jdbc, + UserService userService, + KeyCipher keyCipher, + AppProperties properties, + ObjectMapper objectMapper) { + this.jdbc = jdbc; + this.userService = userService; + this.keyCipher = keyCipher; + this.properties = properties; + this.objectMapper = objectMapper; + this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20)).build(); + } + + /** + * 从项目根目录 Key 文件初始化默认模型。 + * + * @param args 启动参数 + */ + @Override + @Transactional + public void run(ApplicationArguments args) { + Integer count = jdbc.sql("SELECT count(*) FROM app.model_config").query(Integer.class).single(); + if (count > 0 || !Files.isRegularFile(properties.deepseekKeyFile())) { + return; + } + try { + String key = Files.readString(properties.deepseekKeyFile(), StandardCharsets.UTF_8).trim(); + if (key.isBlank()) { + return; + } + UUID adminId = jdbc.sql("SELECT id FROM app.app_user ORDER BY created_at LIMIT 1") + .query(UUID.class) + .single(); + UUID modelId = UUID.randomUUID(); + jdbc.sql(""" + INSERT INTO app.model_config( + id, name, provider, base_url, model_id, api_key_ciphertext, api_key_hint, + key_version, config_json, capabilities_json, is_default, created_by) + VALUES (:id, '默认编排模型', 'OPENAI_COMPATIBLE', :baseUrl, :modelId, + :ciphertext, :hint, 1, CAST(:config AS jsonb), CAST(:capabilities AS jsonb), TRUE, :userId) + """) + .param("id", modelId) + .param("baseUrl", properties.modelBaseUrl()) + .param("modelId", properties.modelId()) + .param("ciphertext", keyCipher.encrypt(key)) + .param("hint", hint(key)) + .param("config", "{\"timeoutSeconds\":120,\"reasoningEffort\":\"high\"}") + .param("capabilities", json(Map.of( + "toolCalling", true, + "reasoning", true, + "contextWindow", properties.modelContextWindow()))) + .param("userId", adminId) + .update(); + for (String role : List.of("ORCHESTRATION", "WRITING", "REVIEW")) { + jdbc.sql("INSERT INTO app.model_assignment(role, model_config_id, assigned_by) VALUES (:role, :id, :userId)") + .param("role", role) + .param("id", modelId) + .param("userId", adminId) + .update(); + } + } catch (IOException exception) { + throw new IllegalStateException("无法读取默认模型 Key", exception); + } + } + + /** + * 列出模型配置,永不返回明文密钥。 + * + * @return 模型列表 + */ + public List list() { + return jdbc.sql(MODEL_SELECT + " ORDER BY is_default DESC, updated_at DESC") + .query(ModelService::mapModel) + .list(); + } + + /** + * 保存新增或已有模型配置。 + * + * @param id 可选模型 ID + * @param input 模型输入 + * @param principal 当前用户 + * @return 保存后的模型 + */ + @Transactional + public ModelView save(UUID id, ModelInput input, Principal principal) { + UUID userId = userService.requireUserId(principal.getName()); + contextWindow(input.capabilities()); + if (id == null) { + if (input.apiKey() == null || input.apiKey().isBlank()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "MODEL_KEY_REQUIRED", "新增模型需要 API Key"); + } + id = UUID.randomUUID(); + jdbc.sql(""" + INSERT INTO app.model_config( + id, name, provider, base_url, model_id, api_key_ciphertext, api_key_hint, + key_version, config_json, capabilities_json, created_by) + VALUES (:id, :name, 'OPENAI_COMPATIBLE', :baseUrl, :modelId, :ciphertext, + :hint, 1, CAST(:config AS jsonb), CAST(:capabilities AS jsonb), :userId) + """) + .param("id", id) + .param("name", input.name().trim()) + .param("baseUrl", normalizeBaseUrl(input.baseUrl())) + .param("modelId", input.modelId().trim()) + .param("ciphertext", keyCipher.encrypt(input.apiKey().trim())) + .param("hint", hint(input.apiKey().trim())) + .param("config", json(input.config())) + .param("capabilities", json(input.capabilities())) + .param("userId", userId) + .update(); + } else { + int updated = input.apiKey() == null || input.apiKey().isBlank() + ? jdbc.sql(""" + UPDATE app.model_config + SET name = :name, base_url = :baseUrl, model_id = :modelId, + config_json = CAST(:config AS jsonb), capabilities_json = CAST(:capabilities AS jsonb), + updated_at = CURRENT_TIMESTAMP + WHERE id = :id + """) + .param("name", input.name().trim()) + .param("baseUrl", normalizeBaseUrl(input.baseUrl())) + .param("modelId", input.modelId().trim()) + .param("config", json(input.config())) + .param("capabilities", json(input.capabilities())) + .param("id", id) + .update() + : jdbc.sql(""" + UPDATE app.model_config + SET name = :name, base_url = :baseUrl, model_id = :modelId, + api_key_ciphertext = :ciphertext, api_key_hint = :hint, key_version = 1, + config_json = CAST(:config AS jsonb), capabilities_json = CAST(:capabilities AS jsonb), + updated_at = CURRENT_TIMESTAMP + WHERE id = :id + """) + .param("name", input.name().trim()) + .param("baseUrl", normalizeBaseUrl(input.baseUrl())) + .param("modelId", input.modelId().trim()) + .param("ciphertext", keyCipher.encrypt(input.apiKey().trim())) + .param("hint", hint(input.apiKey().trim())) + .param("config", json(input.config())) + .param("capabilities", json(input.capabilities())) + .param("id", id) + .update(); + if (updated != 1) { + throw new ApiException(HttpStatus.NOT_FOUND, "MODEL_NOT_FOUND", "模型配置不存在"); + } + } + return require(id); + } + + /** + * 将模型设置为所有角色默认模型。 + * + * @param id 模型 ID + * @param principal 当前用户 + */ + @Transactional + public void setDefault(UUID id, Principal principal) { + require(id); + UUID userId = userService.requireUserId(principal.getName()); + jdbc.sql("UPDATE app.model_config SET is_default = FALSE WHERE is_default").update(); + jdbc.sql("UPDATE app.model_config SET is_default = TRUE, updated_at = CURRENT_TIMESTAMP WHERE id = :id") + .param("id", id) + .update(); + for (String role : List.of("ORCHESTRATION", "WRITING", "REVIEW")) { + jdbc.sql(""" + INSERT INTO app.model_assignment(role, model_config_id, assigned_by) + VALUES (:role, :id, :userId) + ON CONFLICT (role) DO UPDATE + SET model_config_id = EXCLUDED.model_config_id, + assigned_by = EXCLUDED.assigned_by, + updated_at = CURRENT_TIMESTAMP + """) + .param("role", role) + .param("id", id) + .param("userId", userId) + .update(); + } + } + + /** + * 使用最小 Chat Completion 请求测试连接。 + * + * @param id 模型 ID + * @return 测试结果 + */ + public ConnectionResult test(UUID id) { + ModelSecret model = requireSecret(id); + String requestJson = json(Map.of( + "model", model.modelId(), + "messages", List.of(Map.of("role", "user", "content", "回复 OK")), + "max_tokens", 8, + "stream", false)); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(model.baseUrl() + "/chat/completions")) + .timeout(Duration.ofSeconds(30)) + .header("Authorization", "Bearer " + model.apiKey()) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(requestJson)) + .build(); + long started = System.nanoTime(); + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + long elapsed = Duration.ofNanos(System.nanoTime() - started).toMillis(); + if (response.statusCode() < 200 || response.statusCode() >= 300) { + throw new ApiException(HttpStatus.BAD_GATEWAY, "MODEL_CONNECTION_FAILED", + "模型连接失败,服务返回 HTTP " + response.statusCode()); + } + return new ConnectionResult(true, elapsed, "连接正常"); + } catch (IOException exception) { + throw new ApiException(HttpStatus.BAD_GATEWAY, "MODEL_CONNECTION_FAILED", "无法连接模型服务"); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE, "MODEL_CONNECTION_INTERRUPTED", "模型连接测试已中断"); + } + } + + /** + * 获取当前默认模型及明文 Key,仅供模型调用。 + * + * @return 默认模型机密配置 + */ + public ModelSecret defaultModelSecret() { + UUID id = jdbc.sql("SELECT id FROM app.model_config WHERE is_default AND enabled") + .query(UUID.class) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.CONFLICT, "MODEL_NOT_CONFIGURED", "请先配置可用模型")); + return requireSecret(id); + } + + private ModelView require(UUID id) { + return jdbc.sql(MODEL_SELECT + " WHERE id = :id") + .param("id", id) + .query(ModelService::mapModel) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "MODEL_NOT_FOUND", "模型配置不存在")); + } + + private ModelSecret requireSecret(UUID id) { + return jdbc.sql(""" + SELECT id, base_url, model_id, api_key_ciphertext, capabilities_json::text + FROM app.model_config WHERE id = :id AND enabled + """) + .param("id", id) + .query((rs, rowNum) -> new ModelSecret( + rs.getObject("id", UUID.class), + rs.getString("base_url"), + rs.getString("model_id"), + keyCipher.decrypt(rs.getBytes("api_key_ciphertext")), + contextWindow(parseCapabilities(rs.getString("capabilities_json"))))) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "MODEL_NOT_FOUND", "模型配置不存在或已停用")); + } + + /** + * 读取并校验模型上下文窗口。 + * + * @param capabilities 模型能力配置 + * @return 上下文 Token 上限 + */ + private int contextWindow(Map capabilities) { + Object value = capabilities == null ? null : capabilities.get("contextWindow"); + if (!(value instanceof Number number) || number.intValue() < 8_192) { + throw new ApiException( + HttpStatus.BAD_REQUEST, + "MODEL_CONTEXT_WINDOW_INVALID", + "上下文窗口不能小于 8192 Token"); + } + return number.intValue(); + } + + /** + * 解析数据库中的模型能力配置。 + * + * @param json 能力 JSON + * @return 能力键值 + */ + @SuppressWarnings("unchecked") + private Map parseCapabilities(String json) { + try { + return objectMapper.readValue(json, Map.class); + } catch (IOException exception) { + throw new ApiException( + HttpStatus.INTERNAL_SERVER_ERROR, + "MODEL_CAPABILITIES_INVALID", + "模型能力配置无法读取"); + } + } + + private static ModelView mapModel(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + return new ModelView( + rs.getObject("id", UUID.class), + rs.getString("name"), + rs.getString("provider"), + rs.getString("base_url"), + rs.getString("model_id"), + rs.getString("api_key_hint"), + rs.getString("config_json"), + rs.getString("capabilities_json"), + rs.getBoolean("enabled"), + rs.getBoolean("is_default"), + rs.getObject("updated_at", OffsetDateTime.class)); + } + + private String json(Object value) { + try { + return objectMapper.writeValueAsString(value == null ? Map.of() : value); + } catch (IOException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "INVALID_MODEL_CONFIG", "模型配置无法序列化"); + } + } + + private String normalizeBaseUrl(String baseUrl) { + String value = baseUrl.trim(); + while (value.endsWith("/")) { + value = value.substring(0, value.length() - 1); + } + return value; + } + + private static String hint(String key) { + return "••••" + key.substring(Math.max(0, key.length() - 4)); + } + + private static final String MODEL_SELECT = """ + SELECT id, name, provider, base_url, model_id, api_key_hint, config_json, + capabilities_json, enabled, is_default, updated_at + FROM app.model_config + """; + + /** + * 模型编辑输入。 + * + * @param name 配置名称 + * @param baseUrl API 地址 + * @param modelId 模型标识 + * @param apiKey 新密钥;空值表示保留 + * @param config 高级配置 + * @param capabilities 能力声明 + */ + public record ModelInput( + @NotBlank String name, + @NotBlank String baseUrl, + @NotBlank String modelId, + String apiKey, + Map config, + Map capabilities) { + } + + /** + * 对外模型视图。 + * + * @param id 模型 ID + * @param name 配置名称 + * @param provider 服务商 + * @param baseUrl API 地址 + * @param modelId 模型标识 + * @param apiKeyHint 密钥遮罩 + * @param configJson 高级配置 + * @param capabilitiesJson 能力配置 + * @param enabled 是否启用 + * @param defaultModel 是否默认 + * @param updatedAt 更新时间 + */ + public record ModelView( + UUID id, + String name, + String provider, + String baseUrl, + String modelId, + String apiKeyHint, + String configJson, + String capabilitiesJson, + boolean enabled, + boolean defaultModel, + OffsetDateTime updatedAt) { + } + + /** + * 内部模型机密配置。 + * + * @param id 模型 ID + * @param baseUrl API 地址 + * @param modelId 模型标识 + * @param apiKey 明文密钥 + * @param contextWindow 上下文 Token 上限 + */ + public record ModelSecret(UUID id, String baseUrl, String modelId, String apiKey, int contextWindow) { + } + + /** + * 连接测试结果。 + * + * @param success 是否成功 + * @param latencyMs 往返耗时 + * @param message 状态说明 + */ + public record ConnectionResult(boolean success, long latencyMs, String message) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/project/ProjectController.java b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectController.java new file mode 100644 index 0000000..b750eca --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectController.java @@ -0,0 +1,213 @@ +package cn.alphaline.smartfactory.project; + +import cn.alphaline.smartfactory.agent.AgentRunService; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +/** + * 提供项目、规划和企业材料接口。 + */ +@RestController +@RequestMapping("/api/projects") +public class ProjectController { + + private final ProjectService projectService; + private final ProjectFileService fileService; + private final AgentRunService runService; + + /** + * 创建项目控制器。 + * + * @param projectService 项目服务 + * @param fileService 文件服务 + * @param runService Agent Run 服务 + */ + public ProjectController( + ProjectService projectService, + ProjectFileService fileService, + AgentRunService runService) { + this.projectService = projectService; + this.fileService = fileService; + this.runService = runService; + } + + /** + * 列出项目。 + * + * @return 项目列表 + */ + @GetMapping + public List list() { + return projectService.list(); + } + + /** + * 创建项目。 + * + * @param request 创建参数 + * @param principal 当前用户 + * @return 新项目 + */ + @PostMapping + public ProjectService.ProjectView create(@Valid @RequestBody CreateProjectRequest request, Principal principal) { + ProjectService.ProjectView project = projectService.create( + request.companyName(), request.applicationLevel(), principal); + fileService.ensureWorkspace(project.id()); + return project; + } + + /** + * 读取项目详情。 + * + * @param projectId 项目 ID + * @return 项目详情 + */ + @GetMapping("/{projectId}") + public ProjectService.ProjectView get(@PathVariable UUID projectId) { + return projectService.require(projectId); + } + + /** + * 真删除项目、业务记录和工作区文件。 + * + * @param projectId 项目 ID + */ + @DeleteMapping("/{projectId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(@PathVariable UUID projectId) { + projectService.delete(projectId); + fileService.deleteWorkspace(projectId); + } + + /** + * 返回项目当前规划。 + * + * @param projectId 项目 ID + * @return 当前规划;未生成时为空响应体 + */ + @GetMapping("/{projectId}/plan") + public ResponseEntity currentPlan(@PathVariable UUID projectId) { + ProjectService.PlanView plan = projectService.currentPlan(projectId); + return plan == null ? ResponseEntity.noContent().build() : ResponseEntity.ok(plan); + } + + /** + * 确认建设规划。 + * + * @param projectId 项目 ID + * @param request 确认参数 + * @param principal 当前用户 + * @return 已确认规划与已启动的编写 Run + */ + @PostMapping("/{projectId}/plan/confirm") + public AgentRunService.ConfirmPlanResult confirmPlan( + @PathVariable UUID projectId, + @Valid @RequestBody ConfirmPlanRequest request, + Principal principal) { + return runService.confirmPlanAndStartWriting(projectId, request.planId(), request.plan(), principal); + } + + /** + * 上传企业材料。 + * + * @param projectId 项目 ID + * @param file 上传文件 + * @param relativePath 文件夹内相对路径 + * @param principal 当前用户 + * @return 文件元数据 + */ + @PostMapping(path = "/{projectId}/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ProjectFileService.FileView upload( + @PathVariable UUID projectId, + @RequestParam MultipartFile file, + @RequestParam(required = false) String relativePath, + Principal principal) { + return fileService.upload(projectId, file, relativePath, principal); + } + + /** + * 列出企业材料。 + * + * @param projectId 项目 ID + * @return 文件列表 + */ + @GetMapping("/{projectId}/files") + public List files(@PathVariable UUID projectId) { + return fileService.list(projectId); + } + + /** + * 下载企业材料。 + * + * @param projectId 项目 ID + * @param fileId 文件 ID + * @return 文件响应 + */ + @GetMapping("/{projectId}/files/{fileId}/download") + public ResponseEntity download( + @PathVariable UUID projectId, + @PathVariable UUID fileId) { + ProjectFileService.Download download = fileService.download(projectId, fileId); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(download.mimeType())) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename*=UTF-8''" + URLEncoder.encode(download.name(), StandardCharsets.UTF_8)) + .body(download.resource()); + } + + /** + * 返回 document_view 生成的项目内预览图。 + * + * @param projectId 项目 ID + * @param path 工作区相对路径 + * @return 图片响应 + */ + @GetMapping("/{projectId}/view-images") + public ResponseEntity preview( + @PathVariable UUID projectId, + @RequestParam String path) { + ProjectFileService.Preview preview = fileService.preview(projectId, path); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(preview.mimeType())) + .header(HttpHeaders.CACHE_CONTROL, "private, max-age=31536000, immutable") + .body(preview.resource()); + } + + /** + * 项目创建参数。 + * + * @param companyName 企业名称 + * @param applicationLevel 申报等级 + */ + public record CreateProjectRequest(@NotBlank String companyName, String applicationLevel) { + } + + /** + * 规划确认参数。 + * + * @param planId 草稿规划 ID + * @param plan 用户确认后的完整规划 + */ + public record ConfirmPlanRequest(UUID planId, JsonNode plan) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/project/ProjectFileService.java b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectFileService.java new file mode 100644 index 0000000..201577f --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectFileService.java @@ -0,0 +1,438 @@ +package cn.alphaline.smartfactory.project; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.config.AppProperties; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.time.OffsetDateTime; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import org.apache.tika.Tika; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +/** + * 保存、校验和读取项目企业材料。 + */ +@Service +public class ProjectFileService { + + private static final Set ALLOWED_EXTENSIONS = Set.of( + "pdf", "docx", "xls", "xlsx", "pptx", "csv", "txt", "md", + "png", "jpg", "jpeg", "webp", "vsdx", "dwg"); + + private final JdbcClient jdbc; + private final UserService userService; + private final ProjectService projectService; + private final Path dataRoot; + private final Tika tika = new Tika(); + + /** + * 创建材料服务。 + * + * @param jdbc JDBC 客户端 + * @param userService 用户服务 + * @param projectService 项目服务 + * @param properties 应用配置 + */ + public ProjectFileService( + JdbcClient jdbc, + UserService userService, + ProjectService projectService, + AppProperties properties) { + this.jdbc = jdbc; + this.userService = userService; + this.projectService = projectService; + this.dataRoot = properties.dataRoot().toAbsolutePath().normalize(); + } + + /** + * 初始化项目工作区目录。 + * + * @param projectId 项目 ID + */ + public void ensureWorkspace(UUID projectId) { + Path root = projectRoot(projectId); + try { + for (String directory : List.of( + "inputs", "work/facts", "work/plans", "work/drafts", "work/reviews", "work/tmp", + "work/candidates", "references", "artifacts", "skills")) { + Files.createDirectories(root.resolve(directory)); + } + } catch (IOException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "WORKSPACE_CREATE_FAILED", "项目工作区创建失败"); + } + } + + /** + * 删除项目的整个受控工作区。 + * + * @param projectId 项目 ID + * @throws ApiException 文件删除失败时抛出 + */ + public void deleteWorkspace(UUID projectId) { + Path root = projectRoot(projectId); + if (!Files.exists(root)) { + return; + } + try (var paths = Files.walk(root)) { + for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) { + Files.deleteIfExists(path); + } + } catch (IOException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "WORKSPACE_DELETE_FAILED", "项目文件删除失败"); + } + } + + /** + * 上传并校验企业材料。 + * + * @param projectId 项目 ID + * @param file 上传文件 + * @param relativePath 浏览器提供的文件夹内相对路径;单文件上传时可为空 + * @param principal 当前用户 + * @return 文件元数据 + */ + @Transactional + public FileView upload(UUID projectId, MultipartFile file, String relativePath, Principal principal) { + projectService.require(projectId); + String originalName = safeName(file.getOriginalFilename()); + String extension = extension(originalName); + if (!ALLOWED_EXTENSIONS.contains(extension)) { + throw new ApiException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "FILE_TYPE_NOT_ALLOWED", "暂不支持该文件类型"); + } + + ensureWorkspace(projectId); + UUID fileId = UUID.randomUUID(); + String workspacePath = normalizeUploadPath(relativePath, originalName); + Path target = safeProjectPath(projectId, workspacePath); + Path temporary = target.resolveSibling(target.getFileName() + ".uploading-" + fileId); + boolean moved = false; + try { + Files.createDirectories(target.getParent()); + if (Files.exists(target)) { + throw new ApiException(HttpStatus.CONFLICT, "FILE_ALREADY_EXISTS", "文件夹中存在同名文件"); + } + String mime; + try (InputStream input = file.getInputStream()) { + mime = tika.detect(input, originalName); + } + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestInputStream input = new DigestInputStream(file.getInputStream(), digest)) { + Files.copy(input, temporary); + } + Files.move(temporary, target); + moved = true; + UUID userId = userService.requireUserId(principal.getName()); + jdbc.sql(""" + INSERT INTO app.project_file( + id, project_id, original_name, stored_name, relative_path, mime_type, + extension, size_bytes, sha256, uploaded_by) + VALUES (:id, :projectId, :originalName, :storedName, :relativePath, :mimeType, + :extension, :sizeBytes, :sha256, :userId) + """) + .param("id", fileId) + .param("projectId", projectId) + .param("originalName", originalName) + .param("storedName", target.getFileName().toString()) + .param("relativePath", workspacePath) + .param("mimeType", mime) + .param("extension", extension) + .param("sizeBytes", Files.size(target)) + .param("sha256", HexFormat.of().formatHex(digest.digest())) + .param("userId", userId) + .update(); + return require(fileId); + } catch (FileAlreadyExistsException exception) { + cleanupFailedUpload(exception, temporary); + throw new ApiException(HttpStatus.CONFLICT, "FILE_ALREADY_EXISTS", "文件夹中存在同名文件"); + } catch (IOException | NoSuchAlgorithmException exception) { + cleanupFailedUpload(exception, moved ? new Path[]{temporary, target} : new Path[]{temporary}); + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "FILE_STORE_FAILED", "文件保存失败"); + } catch (RuntimeException exception) { + cleanupFailedUpload(exception, moved ? new Path[]{temporary, target} : new Path[]{temporary}); + throw exception; + } + } + + /** + * 清理未完成上传留下的临时文件或孤儿正式文件。 + * + * @param failure 原始异常 + * @param paths 待清理路径 + */ + private void cleanupFailedUpload(Throwable failure, Path... paths) { + for (Path path : paths) { + try { + Files.deleteIfExists(path); + } catch (IOException cleanupException) { + failure.addSuppressed(cleanupException); + } + } + } + + /** + * 列出项目有效材料。 + * + * @param projectId 项目 ID + * @return 文件元数据列表 + */ + public List list(UUID projectId) { + projectService.require(projectId); + return jdbc.sql(""" + SELECT id, project_id, original_name, relative_path, mime_type, extension, + size_bytes, status, created_at + FROM app.project_file + WHERE project_id = :projectId AND deleted_at IS NULL + ORDER BY relative_path + """) + .param("projectId", projectId) + .query(ProjectFileService::mapFile) + .list(); + } + + /** + * 获取材料下载资源。 + * + * @param projectId 项目 ID + * @param fileId 文件 ID + * @return 文件资源 + */ + public Download download(UUID projectId, UUID fileId) { + StoredFile stored = jdbc.sql(""" + SELECT original_name, relative_path, mime_type + FROM app.project_file + WHERE id = :fileId AND project_id = :projectId AND deleted_at IS NULL AND status = 'READY' + """) + .param("fileId", fileId) + .param("projectId", projectId) + .query((rs, rowNum) -> new StoredFile( + rs.getString("original_name"), rs.getString("relative_path"), rs.getString("mime_type"))) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "FILE_NOT_FOUND", "文件不存在")); + try { + Resource resource = new UrlResource(safeProjectPath(projectId, stored.relativePath()).toUri()); + if (!resource.exists()) { + throw new ApiException(HttpStatus.NOT_FOUND, "FILE_NOT_FOUND", "文件内容不存在"); + } + return new Download(stored.originalName(), stored.mimeType(), resource); + } catch (java.net.MalformedURLException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "FILE_PATH_INVALID", "文件路径无效"); + } + } + + /** + * 读取 document_view 生成的项目内预览图。 + * + * @param projectId 项目 ID + * @param relativePath 工作区相对路径 + * @return 预览图资源 + * @throws ApiException 路径非法或图片不存在时抛出 + */ + public Preview preview(UUID projectId, String relativePath) { + projectService.require(projectId); + String normalized = relativePath == null ? "" : relativePath.replace('\\', '/'); + if (!normalized.startsWith("work/tmp/document-view/") + || !(normalized.endsWith(".png") || normalized.endsWith(".jpg") || normalized.endsWith(".jpeg"))) { + throw new ApiException(HttpStatus.BAD_REQUEST, "PREVIEW_PATH_INVALID", "预览图路径无效"); + } + Path path = safeProjectPath(projectId, normalized); + if (!Files.isRegularFile(path)) { + throw new ApiException(HttpStatus.NOT_FOUND, "PREVIEW_NOT_FOUND", "预览图不存在"); + } + try { + String mimeType = Files.probeContentType(path); + return new Preview(mimeType == null ? "image/png" : mimeType, new UrlResource(path.toUri())); + } catch (IOException exception) { + throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "PREVIEW_READ_FAILED", "预览图读取失败"); + } + } + + /** + * 返回规范化项目根目录。 + * + * @param projectId 项目 ID + * @return 项目根目录 + */ + public Path projectRoot(UUID projectId) { + return dataRoot.resolve("projects").resolve(projectId.toString()).normalize(); + } + + /** + * 在项目根目录内解析相对路径。 + * + * @param projectId 项目 ID + * @param relativePath 相对路径 + * @return 安全绝对路径 + */ + public Path safeProjectPath(UUID projectId, String relativePath) { + Path root = projectRoot(projectId); + Path result = root.resolve(relativePath).normalize(); + if (!result.startsWith(root)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "PATH_OUTSIDE_PROJECT", "文件路径超出项目范围"); + } + verifyExistingParent(root, result); + return result; + } + + /** + * 拒绝通过现有符号链接把后续路径解析到项目目录之外。 + * + * @param root 项目根目录 + * @param result 待使用路径 + */ + private void verifyExistingParent(Path root, Path result) { + try { + Path existing = result; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing != null && !existing.toRealPath().startsWith(root.toRealPath())) { + throw new ApiException(HttpStatus.BAD_REQUEST, "PATH_OUTSIDE_PROJECT", "文件路径超出项目范围"); + } + } catch (IOException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_INVALID", "文件路径无效"); + } + } + + private FileView require(UUID fileId) { + return jdbc.sql(""" + SELECT id, project_id, original_name, relative_path, mime_type, extension, + size_bytes, status, created_at + FROM app.project_file WHERE id = :id + """) + .param("id", fileId) + .query(ProjectFileService::mapFile) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "FILE_NOT_FOUND", "文件不存在")); + } + + private static FileView mapFile(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + return new FileView( + rs.getObject("id", UUID.class), + rs.getObject("project_id", UUID.class), + rs.getString("original_name"), + rs.getString("relative_path"), + rs.getString("mime_type"), + rs.getString("extension"), + rs.getLong("size_bytes"), + rs.getString("status"), + rs.getObject("created_at", OffsetDateTime.class)); + } + + private String safeName(String originalName) { + if (originalName == null || originalName.isBlank()) { + return "未命名文件"; + } + return Path.of(originalName).getFileName().toString().replaceAll("[\\r\\n]", "_"); + } + + /** + * 规范化上传路径并保留用户选择的文件夹层级。 + * + * @param suppliedPath 浏览器提供的文件夹内路径 + * @param originalName 原始文件名 + * @return 相对于项目根目录的 inputs 路径 + * @throws ApiException 路径越界、过长或文件名不一致时抛出 + */ + String normalizeUploadPath(String suppliedPath, String originalName) { + String candidate = suppliedPath == null || suppliedPath.isBlank() + ? originalName + : suppliedPath.replace('\\', '/'); + if (candidate.startsWith("/") || candidate.indexOf('\0') >= 0) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_INVALID", "文件夹路径无效"); + } + Path path; + try { + path = Path.of(candidate).normalize(); + } catch (RuntimeException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_INVALID", "文件夹路径无效"); + } + if (path.isAbsolute() || path.getNameCount() == 0 || path.startsWith("..") + || !path.getFileName().toString().equals(originalName)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_INVALID", "文件夹路径无效"); + } + for (Path segment : path) { + String value = segment.toString(); + if (value.isBlank() || ".".equals(value) || "..".equals(value) + || value.getBytes(StandardCharsets.UTF_8).length > 255) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_INVALID", "文件夹路径无效"); + } + } + String result = "inputs/" + path.toString().replace('\\', '/'); + if (result.length() > 1_000 || originalName.length() > 500) { + throw new ApiException(HttpStatus.BAD_REQUEST, "FILE_PATH_TOO_LONG", "文件夹路径过长"); + } + return result; + } + + private String extension(String name) { + int dot = name.lastIndexOf('.'); + return dot < 0 ? "" : name.substring(dot + 1).toLowerCase(Locale.ROOT); + } + + /** + * 企业材料元数据。 + * + * @param id 文件 ID + * @param projectId 项目 ID + * @param name 原始文件名 + * @param relativePath 工作区相对路径 + * @param mimeType 检测到的 MIME + * @param extension 扩展名 + * @param sizeBytes 文件大小 + * @param status 文件状态 + * @param createdAt 上传时间 + */ + public record FileView( + UUID id, + UUID projectId, + String name, + String relativePath, + String mimeType, + String extension, + long sizeBytes, + String status, + OffsetDateTime createdAt) { + } + + /** + * 下载结果。 + * + * @param name 下载文件名 + * @param mimeType MIME 类型 + * @param resource 文件资源 + */ + public record Download(String name, String mimeType, Resource resource) { + } + + /** + * 文档视觉预览结果。 + * + * @param mimeType 图片 MIME 类型 + * @param resource 图片资源 + */ + public record Preview(String mimeType, Resource resource) { + } + + private record StoredFile(String originalName, String relativePath, String mimeType) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/project/ProjectService.java b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectService.java new file mode 100644 index 0000000..59c2ed8 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/project/ProjectService.java @@ -0,0 +1,326 @@ +package cn.alphaline.smartfactory.project; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.security.Principal; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 管理企业项目和不可变规划版本。 + */ +@Service +public class ProjectService { + + private final JdbcClient jdbc; + private final UserService userService; + private final ObjectMapper objectMapper; + + /** + * 创建项目服务。 + * + * @param jdbc JDBC 客户端 + * @param userService 用户服务 + * @param objectMapper JSON 映射器 + */ + public ProjectService(JdbcClient jdbc, UserService userService, ObjectMapper objectMapper) { + this.jdbc = jdbc; + this.userService = userService; + this.objectMapper = objectMapper; + } + + /** + * 创建企业申报项目。 + * + * @param companyName 企业名称 + * @param applicationLevel 申报等级 + * @param principal 当前用户 + * @return 新项目 + */ + @Transactional + public ProjectView create(String companyName, String applicationLevel, Principal principal) { + String level = normalizeLevel(applicationLevel); + UUID id = UUID.randomUUID(); + UUID userId = userService.requireUserId(principal.getName()); + String threadId = "project-" + id; + jdbc.sql(""" + INSERT INTO app.project( + id, company_name, project_name, agui_thread_id, application_level, created_by) + VALUES (:id, :companyName, :projectName, :threadId, :level, :userId) + """) + .param("id", id) + .param("companyName", companyName.trim()) + .param("projectName", companyName.trim()) + .param("threadId", threadId) + .param("level", level) + .param("userId", userId) + .update(); + return require(id); + } + + /** + * 列出最近项目。 + * + * @return 按更新时间倒序的项目 + */ + public List list() { + return jdbc.sql(PROJECT_SELECT + " ORDER BY updated_at DESC") + .query(ProjectService::mapProject) + .list(); + } + + /** + * 读取一个项目。 + * + * @param projectId 项目 ID + * @return 项目详情 + * @throws ApiException 项目不存在时抛出 + */ + public ProjectView require(UUID projectId) { + return jdbc.sql(PROJECT_SELECT + " WHERE id = :id") + .param("id", projectId) + .query(ProjectService::mapProject) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "PROJECT_NOT_FOUND", "项目不存在")); + } + + /** + * 真删除项目及其全部业务记录。 + * + * @param projectId 项目 ID + * @throws ApiException 项目不存在或仍有 Agent 正在执行时抛出 + */ + @Transactional + public void delete(UUID projectId) { + require(projectId); + boolean running = jdbc.sql(""" + SELECT EXISTS( + SELECT 1 FROM app.agent_run WHERE project_id = :projectId AND status = 'RUNNING' + ) + """) + .param("projectId", projectId) + .query(Boolean.class) + .single(); + if (running) { + throw new ApiException(HttpStatus.CONFLICT, "PROJECT_RUN_ACTIVE", "请先停止正在执行的任务"); + } + + for (String table : List.of("agent_event", "artifact", "project_plan", "project_file", "agent_run")) { + jdbc.sql("DELETE FROM app." + table + " WHERE project_id = :projectId") + .param("projectId", projectId) + .update(); + } + int deleted = jdbc.sql("DELETE FROM app.project WHERE id = :projectId") + .param("projectId", projectId) + .update(); + if (deleted != 1) { + throw new ApiException(HttpStatus.NOT_FOUND, "PROJECT_NOT_FOUND", "项目不存在"); + } + } + + /** + * 更新项目业务阶段。 + * + * @param projectId 项目 ID + * @param status 新阶段 + */ + public void updateStatus(UUID projectId, String status) { + int updated = jdbc.sql(""" + UPDATE app.project + SET status = :status, version = version + 1, updated_at = CURRENT_TIMESTAMP + WHERE id = :id + """) + .param("status", status) + .param("id", projectId) + .update(); + if (updated != 1) { + throw new ApiException(HttpStatus.NOT_FOUND, "PROJECT_NOT_FOUND", "项目不存在"); + } + } + + /** + * 保存 Agent 生成的规划草稿。 + * + * @param projectId 项目 ID + * @param plan 规划 JSON + * @param userId 创建人 + * @return 规划版本 + */ + @Transactional + public PlanView saveDraftPlan(UUID projectId, JsonNode plan, UUID userId) { + Integer version = jdbc.sql("SELECT COALESCE(MAX(plan_version), 0) + 1 FROM app.project_plan WHERE project_id = :id") + .param("id", projectId) + .query(Integer.class) + .single(); + UUID planId = UUID.randomUUID(); + jdbc.sql(""" + INSERT INTO app.project_plan(id, project_id, plan_version, status, plan_json, created_by) + VALUES (:id, :projectId, :version, 'DRAFT', CAST(:plan AS jsonb), :userId) + """) + .param("id", planId) + .param("projectId", projectId) + .param("version", version) + .param("plan", plan.toString()) + .param("userId", userId) + .update(); + updateStatus(projectId, "PLANNING"); + return requirePlan(planId); + } + + /** + * 返回项目当前规划。 + * + * @param projectId 项目 ID + * @return 最新规划;不存在时返回空 + */ + public PlanView currentPlan(UUID projectId) { + return jdbc.sql(""" + SELECT id, project_id, plan_version, status, plan_json, confirmed_at, created_at + FROM app.project_plan + WHERE project_id = :projectId + ORDER BY CASE status WHEN 'CONFIRMED' THEN 0 ELSE 1 END, plan_version DESC + LIMIT 1 + """) + .param("projectId", projectId) + .query(this::mapPlan) + .optional() + .orElse(null); + } + + /** + * 确认规划并冻结其内容。 + * + * @param projectId 项目 ID + * @param planId 草稿规划 ID + * @param plan 用户确认后的完整规划 + * @param principal 当前用户 + * @return 已确认规划 + */ + @Transactional + public PlanView confirmPlan(UUID projectId, UUID planId, JsonNode plan, Principal principal) { + UUID userId = userService.requireUserId(principal.getName()); + int updated = jdbc.sql(""" + UPDATE app.project_plan + SET status = 'CONFIRMED', plan_json = CAST(:plan AS jsonb), confirmed_by = :userId, + confirmed_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE id = :planId AND project_id = :projectId AND status = 'DRAFT' + """) + .param("plan", plan.toString()) + .param("userId", userId) + .param("planId", planId) + .param("projectId", projectId) + .update(); + if (updated != 1) { + throw new ApiException(HttpStatus.CONFLICT, "PLAN_ALREADY_CONFIRMED", "规划已确认或版本不存在"); + } + updateStatus(projectId, "WRITING"); + return requirePlan(planId); + } + + private PlanView requirePlan(UUID planId) { + return jdbc.sql(""" + SELECT id, project_id, plan_version, status, plan_json, confirmed_at, created_at + FROM app.project_plan WHERE id = :id + """) + .param("id", planId) + .query(this::mapPlan) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "PLAN_NOT_FOUND", "规划不存在")); + } + + private PlanView mapPlan(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + try { + return new PlanView( + rs.getObject("id", UUID.class), + rs.getObject("project_id", UUID.class), + rs.getInt("plan_version"), + rs.getString("status"), + objectMapper.readTree(rs.getString("plan_json")), + rs.getObject("confirmed_at", OffsetDateTime.class), + rs.getObject("created_at", OffsetDateTime.class)); + } catch (JsonProcessingException exception) { + throw new java.sql.SQLException("规划 JSON 无法解析", exception); + } + } + + private static ProjectView mapProject(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + return new ProjectView( + rs.getObject("id", UUID.class), + rs.getString("company_name"), + rs.getString("project_name"), + rs.getString("agui_thread_id"), + rs.getString("application_level"), + rs.getString("status"), + rs.getLong("version"), + rs.getObject("created_at", OffsetDateTime.class), + rs.getObject("updated_at", OffsetDateTime.class)); + } + + private String normalizeLevel(String level) { + String value = level == null ? "ADVANCED" : level.trim().toUpperCase(java.util.Locale.ROOT); + if (!value.equals("ADVANCED") && !value.equals("EXCELLENT")) { + throw new ApiException(HttpStatus.BAD_REQUEST, "INVALID_APPLICATION_LEVEL", "申报等级无效"); + } + return value; + } + + private static final String PROJECT_SELECT = """ + SELECT id, company_name, project_name, agui_thread_id, application_level, status, + version, created_at, updated_at + FROM app.project + """; + + /** + * 项目视图。 + * + * @param id 项目 ID + * @param companyName 企业名称 + * @param projectName 项目名称 + * @param threadId AG-UI 线程 ID + * @param applicationLevel 申报等级 + * @param status 当前状态 + * @param version 乐观锁版本 + * @param createdAt 创建时间 + * @param updatedAt 更新时间 + */ + public record ProjectView( + UUID id, + String companyName, + String projectName, + String threadId, + String applicationLevel, + String status, + long version, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + } + + /** + * 规划版本视图。 + * + * @param id 规划 ID + * @param projectId 项目 ID + * @param version 版本号 + * @param status 规划状态 + * @param plan 规划 JSON + * @param confirmedAt 确认时间 + * @param createdAt 创建时间 + */ + public record PlanView( + UUID id, + UUID projectId, + int version, + String status, + JsonNode plan, + OffsetDateTime confirmedAt, + OffsetDateTime createdAt) { + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/skill/SkillController.java b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillController.java new file mode 100644 index 0000000..0580c89 --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillController.java @@ -0,0 +1,113 @@ +package cn.alphaline.smartfactory.skill; + +import java.security.Principal; +import java.util.List; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +/** + * 提供 Skill 导入、查看和启停接口。 + */ +@RestController +@RequestMapping("/api/skills") +public class SkillController { + + private final SkillService skillService; + + /** + * 创建 Skill 控制器。 + * + * @param skillService Skill 服务 + */ + public SkillController(SkillService skillService) { + this.skillService = skillService; + } + + /** + * 列出 Skill。 + * + * @return Skill 列表 + */ + @GetMapping + public List list() { + return skillService.list(); + } + + /** + * 读取 Skill 详情。 + * + * @param name Skill 名称 + * @return Skill 详情 + */ + @GetMapping("/{name}") + public SkillService.SkillDetail get(@PathVariable String name) { + return skillService.require(name); + } + + /** + * 读取一个文本资源。 + * + * @param name Skill 名称 + * @param path 资源路径 + * @return 资源正文 + */ + @GetMapping("/{name}/resource") + public String resource(@PathVariable String name, @RequestParam String path) { + return skillService.resource(name, path); + } + + /** + * 导入 Skill ZIP。 + * + * @param file ZIP 文件 + * @param principal 当前用户 + * @return 导入后的 Skill + */ + @PostMapping(path = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @ResponseStatus(HttpStatus.CREATED) + public SkillService.SkillView importZip(@RequestParam MultipartFile file, Principal principal) { + return skillService.importZip(file, principal); + } + + /** + * 启用 Skill。 + * + * @param name Skill 名称 + */ + @PostMapping("/{name}/enable") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void enable(@PathVariable String name) { + skillService.setEnabled(name, true); + } + + /** + * 停用 Skill。 + * + * @param name Skill 名称 + */ + @PostMapping("/{name}/disable") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void disable(@PathVariable String name) { + skillService.setEnabled(name, false); + } + + /** + * 删除用户导入 Skill。 + * + * @param name Skill 名称 + */ + @DeleteMapping("/{name}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(@PathVariable String name) { + skillService.deleteImported(name); + } +} diff --git a/server/src/main/java/cn/alphaline/smartfactory/skill/SkillPackageReader.java b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillPackageReader.java new file mode 100644 index 0000000..a36fabd --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillPackageReader.java @@ -0,0 +1,149 @@ +package cn.alphaline.smartfactory.skill; + +import cn.alphaline.smartfactory.common.ApiException; +import io.agentscope.core.skill.AgentSkill; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +/** + * 读取并校验标准 Skill 目录。 + */ +@Component +public class SkillPackageReader { + + private static final Pattern FRONTMATTER = Pattern.compile("\\A---\\s*\\R(.*?)\\R---\\s*\\R", Pattern.DOTALL); + private static final Pattern FIELD = Pattern.compile("(?m)^([A-Za-z][A-Za-z0-9_-]*):\\s*(.+?)\\s*$"); + + /** + * 读取一个 Skill 目录。 + * + * @param directory Skill 根目录 + * @param source 仓库来源 + * @return 已校验 Skill 包 + */ + public SkillPackage read(Path directory, String source) { + Path root = directory.toAbsolutePath().normalize(); + Path skillFile = root.resolve("SKILL.md"); + if (!Files.isRegularFile(skillFile)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_FILE_MISSING", "Skill 缺少 SKILL.md"); + } + try { + List files = Files.walk(root) + .filter(Files::isRegularFile) + .filter(path -> !isHidden(root.relativize(path))) + .sorted(Comparator.comparing(path -> normalize(root.relativize(path)))) + .toList(); + if (files.size() > 500) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_TOO_MANY_FILES", "Skill 文件数量超过限制"); + } + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + Map resources = new HashMap<>(); + String content = null; + for (Path file : files) { + String relative = normalize(root.relativize(file)); + byte[] bytes = Files.readAllBytes(file); + String text = decodeUtf8(bytes, relative); + digest.update(relative.getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + digest.update(bytes); + if (relative.equals("SKILL.md")) { + content = text; + } else { + resources.put(relative, text); + } + } + Map frontmatter = frontmatter(content); + String name = required(frontmatter, "name"); + String description = required(frontmatter, "description"); + String version = frontmatter.getOrDefault("version", "v1.0"); + AgentSkill skill = new AgentSkill(name, description, content, resources, source); + return new SkillPackage(skill, version, HexFormat.of().formatHex(digest.digest()), files.size()); + } catch (IOException | NoSuchAlgorithmException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_READ_FAILED", "Skill 文件读取失败"); + } + } + + private Map frontmatter(String content) { + Matcher block = FRONTMATTER.matcher(content == null ? "" : content); + if (!block.find()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_FRONTMATTER_MISSING", "SKILL.md 缺少 YAML Frontmatter"); + } + Map values = new HashMap<>(); + Matcher field = FIELD.matcher(block.group(1)); + while (field.find()) { + values.put(field.group(1), unquote(field.group(2).trim())); + } + return values; + } + + private String required(Map values, String key) { + String value = values.get(key); + if (value == null || value.isBlank()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_FRONTMATTER_INVALID", "SKILL.md 缺少 " + key); + } + return value; + } + + private String decodeUtf8(byte[] bytes, String path) { + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_BINARY_RESOURCE", "Skill 资源必须是 UTF-8 文本:" + path); + } + } + + private boolean isHidden(Path relative) { + for (Path part : relative) { + if (part.toString().startsWith(".")) { + return true; + } + } + return false; + } + + private String normalize(Path path) { + return path.toString().replace('\\', '/'); + } + + private String unquote(String value) { + if (value.length() >= 2 + && ((value.startsWith("\"") && value.endsWith("\"")) + || (value.startsWith("'") && value.endsWith("'")))) { + return value.substring(1, value.length() - 1); + } + return value; + } + + /** + * 已解析 Skill 包。 + * + * @param skill AgentScope Skill + * @param version 展示版本 + * @param checksum 目录校验和 + * @param fileCount 文件数 + */ + public record SkillPackage(AgentSkill skill, String version, String checksum, int fileCount) { + } +} + diff --git a/server/src/main/java/cn/alphaline/smartfactory/skill/SkillService.java b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillService.java new file mode 100644 index 0000000..067dd2d --- /dev/null +++ b/server/src/main/java/cn/alphaline/smartfactory/skill/SkillService.java @@ -0,0 +1,368 @@ +package cn.alphaline.smartfactory.skill; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.common.ApiException; +import cn.alphaline.smartfactory.config.AppProperties; +import io.agentscope.core.skill.AgentSkill; +import io.agentscope.core.skill.repository.postgresql.PostgresSkillRepository; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.Principal; +import java.time.OffsetDateTime; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +/** + * 提供 Skill 查看、导入和启停能力。 + */ +@Service +public class SkillService { + + private static final int MAX_ZIP_ENTRIES = 500; + private static final long MAX_UNCOMPRESSED_BYTES = 20L * 1024 * 1024; + + private final JdbcClient jdbc; + private final PostgresSkillRepository repository; + private final SkillPackageReader packageReader; + private final UserService userService; + private final AppProperties properties; + + /** + * 创建 Skill 服务。 + * + * @param jdbc JDBC 客户端 + * @param repository AgentScope PostgreSQL 仓库 + * @param packageReader Skill 包读取器 + * @param userService 用户服务 + * @param properties 应用配置 + */ + public SkillService( + JdbcClient jdbc, + PostgresSkillRepository repository, + SkillPackageReader packageReader, + UserService userService, + AppProperties properties) { + this.jdbc = jdbc; + this.repository = repository; + this.packageReader = packageReader; + this.userService = userService; + this.properties = properties; + } + + /** + * 列出 Skill 配置。 + * + * @return Skill 列表 + */ + public List list() { + return jdbc.sql(SKILL_SELECT + " ORDER BY c.source_type, s.name") + .query(SkillService::mapSkill) + .list(); + } + + /** + * 读取 Skill 详情。 + * + * @param name Skill 名称 + * @return Skill 详情 + */ + public SkillDetail require(String name) { + SkillView view = jdbc.sql(SKILL_SELECT + " WHERE s.name = :name") + .param("name", name) + .query(SkillService::mapSkill) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "SKILL_NOT_FOUND", "Skill 不存在")); + AgentSkill skill = repository.getSkill(name); + if (skill == null) { + throw new ApiException(HttpStatus.NOT_FOUND, "SKILL_NOT_FOUND", "Skill 内容不存在"); + } + return new SkillDetail(view, skill.getSkillContent(), skill.getResourcePaths().stream().sorted().toList()); + } + + /** + * 读取 Skill 文本资源。 + * + * @param name Skill 名称 + * @param path 资源相对路径 + * @return 资源文本 + */ + public String resource(String name, String path) { + if (path == null || path.isBlank() || path.startsWith("/") || path.contains("..")) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_RESOURCE_PATH_INVALID", "Skill 资源路径无效"); + } + AgentSkill skill = repository.getSkill(name); + String resource = skill == null ? null : skill.getResource(path); + if (resource == null) { + throw new ApiException(HttpStatus.NOT_FOUND, "SKILL_RESOURCE_NOT_FOUND", "Skill 资源不存在"); + } + return resource; + } + + /** + * 设置 Skill 启用状态。 + * + * @param name Skill 名称 + * @param enabled 是否启用 + */ + public void setEnabled(String name, boolean enabled) { + int updated = jdbc.sql(""" + UPDATE app.skill_config SET enabled = :enabled, updated_at = CURRENT_TIMESTAMP + WHERE skill_name = :name AND validation_status = 'VALID' + """) + .param("enabled", enabled) + .param("name", name) + .update(); + if (updated != 1) { + throw new ApiException(HttpStatus.NOT_FOUND, "SKILL_NOT_FOUND", "Skill 不存在或校验未通过"); + } + } + + + /** + * 返回当前启用的 Skill 名称。 + * + * @return Skill 名称数组 + */ + public String[] enabledNames() { + return jdbc.sql(""" + SELECT skill_name FROM app.skill_config + WHERE enabled AND validation_status = 'VALID' + ORDER BY skill_name + """) + .query(String.class) + .list() + .toArray(String[]::new); + } + + /** + * 导入管理员上传的标准 Skill ZIP。 + * + * @param file ZIP 文件 + * @param principal 当前用户 + * @return 导入后的 Skill + */ + @Transactional + public SkillView importZip(MultipartFile file, Principal principal) { + if (file.isEmpty()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_ZIP_EMPTY", "Skill 压缩包为空"); + } + Path importRoot = properties.dataRoot().toAbsolutePath().normalize().resolve("skill-imports"); + try { + Files.createDirectories(importRoot); + Path temporary = Files.createTempDirectory(importRoot, "skill-"); + try { + unzip(file, temporary); + Path skillRoot = locateSkillRoot(temporary); + SkillPackageReader.SkillPackage skillPackage = packageReader.read(skillRoot, "imported"); + String name = skillPackage.skill().getName(); + if (repository.skillExists(name)) { + throw new ApiException(HttpStatus.CONFLICT, "SKILL_NAME_CONFLICT", "同名 Skill 已存在"); + } + repository.save(List.of(skillPackage.skill()), false); + UUID userId = userService.requireUserId(principal.getName()); + jdbc.sql(""" + INSERT INTO app.skill_config( + skill_name, version, source_type, enabled, read_only, checksum, + validation_status, imported_by) + VALUES (:name, :version, 'IMPORTED', FALSE, TRUE, :checksum, 'VALID', :userId) + """) + .param("name", name) + .param("version", skillPackage.version()) + .param("checksum", skillPackage.checksum()) + .param("userId", userId) + .update(); + return require(name).view(); + } finally { + deleteTree(temporary); + } + } catch (IOException exception) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_IMPORT_FAILED", "Skill 压缩包读取失败"); + } + } + + /** + * 删除管理员导入且已停用的 Skill。 + * + * @param name Skill 名称 + */ + @Transactional + public void deleteImported(String name) { + String sourceType = jdbc.sql("SELECT source_type FROM app.skill_config WHERE skill_name = :name") + .param("name", name) + .query(String.class) + .optional() + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "SKILL_NOT_FOUND", "Skill 不存在")); + if (!"IMPORTED".equals(sourceType)) { + throw new ApiException(HttpStatus.CONFLICT, "BUILTIN_SKILL_READ_ONLY", "内置 Skill 不能删除"); + } + repository.delete(name); + } + + /** + * 解压 Skill 包,并忽略 macOS 与 Python 生成的无关元数据。 + * + * @param file ZIP 文件 + * @param destination 解压目录 + * @throws IOException ZIP 读取或文件写入失败时抛出 + */ + static void unzip(MultipartFile file, Path destination) throws IOException { + int entries = 0; + long total = 0; + Path root = destination.toAbsolutePath().normalize(); + try (InputStream source = file.getInputStream(); ZipInputStream zip = new ZipInputStream(source, java.nio.charset.StandardCharsets.UTF_8)) { + ZipEntry entry; + byte[] buffer = new byte[8192]; + while ((entry = zip.getNextEntry()) != null) { + String entryName = entry.getName().replace('\\', '/'); + Path target = root.resolve(entryName).normalize(); + if (!target.startsWith(root)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_ZIP_PATH_INVALID", "Skill 压缩包包含越界路径"); + } + if (isIgnoredArchiveEntry(entryName)) { + continue; + } + if (++entries > MAX_ZIP_ENTRIES) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_ZIP_TOO_MANY_FILES", "Skill 压缩包文件数量超过限制"); + } + if (entry.isDirectory()) { + Files.createDirectories(target); + continue; + } + Files.createDirectories(target.getParent()); + try (java.io.OutputStream output = Files.newOutputStream(target)) { + int read; + while ((read = zip.read(buffer)) != -1) { + total += read; + if (total > MAX_UNCOMPRESSED_BYTES) { + throw new ApiException(HttpStatus.PAYLOAD_TOO_LARGE, "SKILL_ZIP_TOO_LARGE", "Skill 解压后大小超过限制"); + } + output.write(buffer, 0, read); + } + } + } + } + } + + /** + * 根据唯一的 SKILL.md 定位 Skill 根目录。 + * + * @param temporary ZIP 解压目录 + * @return Skill 根目录 + * @throws IOException 目录遍历失败时抛出 + */ + static Path locateSkillRoot(Path temporary) throws IOException { + if (Files.isRegularFile(temporary.resolve("SKILL.md"))) { + return temporary; + } + List candidates; + try (var paths = Files.walk(temporary)) { + candidates = paths + .filter(path -> Files.isRegularFile(path) && path.getFileName().toString().equals("SKILL.md")) + .map(Path::getParent) + .distinct() + .toList(); + } + if (candidates.size() == 1) { + return candidates.getFirst(); + } + if (candidates.isEmpty()) { + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_STRUCTURE_INVALID", "压缩包中必须包含 SKILL.md"); + } + throw new ApiException(HttpStatus.BAD_REQUEST, "SKILL_STRUCTURE_INVALID", "压缩包中包含多个 Skill,请每次仅导入一个"); + } + + private static boolean isIgnoredArchiveEntry(String entryName) { + String lowerName = entryName.toLowerCase(Locale.ROOT); + if (lowerName.endsWith(".pyc")) { + return true; + } + for (String part : entryName.split("/")) { + if (part.equals("__MACOSX") + || part.equals(".DS_Store") + || part.equals("__pycache__") + || part.startsWith("._")) { + return true; + } + } + return false; + } + + private void deleteTree(Path root) { + if (root == null || !Files.exists(root)) { + return; + } + try { + for (Path path : Files.walk(root).sorted(Comparator.reverseOrder()).toList()) { + Files.deleteIfExists(path); + } + } catch (IOException ignored) { + // 临时目录清理失败不覆盖主要导入结果,后续维护任务可清理。 + } + } + + private static SkillView mapSkill(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException { + return new SkillView( + rs.getString("name"), + rs.getString("description"), + rs.getString("version"), + rs.getString("source_type"), + rs.getBoolean("enabled"), + rs.getBoolean("read_only"), + rs.getString("validation_status"), + rs.getString("validation_message"), + rs.getObject("updated_at", OffsetDateTime.class)); + } + + private static final String SKILL_SELECT = """ + SELECT s.name, s.description, c.version, c.source_type, c.enabled, c.read_only, + c.validation_status, c.validation_message, c.updated_at + FROM agentscope.agentscope_skills s + JOIN app.skill_config c ON c.skill_name = s.name + """; + + /** + * Skill 列表视图。 + * + * @param name 标准名称 + * @param description 描述 + * @param version 版本 + * @param sourceType 来源 + * @param enabled 是否启用 + * @param readOnly 是否只读 + * @param validationStatus 校验状态 + * @param validationMessage 校验信息 + * @param updatedAt 更新时间 + */ + public record SkillView( + String name, + String description, + String version, + String sourceType, + boolean enabled, + boolean readOnly, + String validationStatus, + String validationMessage, + OffsetDateTime updatedAt) { + } + + /** + * Skill 详情。 + * + * @param view 基本信息 + * @param content SKILL.md 全文 + * @param resources 资源路径 + */ + public record SkillDetail(SkillView view, String content, List resources) { + } +} diff --git a/server/src/main/resources/application.yml b/server/src/main/resources/application.yml new file mode 100644 index 0000000..2c9d6c1 --- /dev/null +++ b/server/src/main/resources/application.yml @@ -0,0 +1,49 @@ +spring: + application: + name: smart-factory-approval-agent + datasource: + url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:54330/smart_factory_agent} + username: ${SPRING_DATASOURCE_USERNAME:smart_factory} + password: ${SPRING_DATASOURCE_PASSWORD:smart_factory} + hikari: + maximum-pool-size: 12 + minimum-idle: 2 + flyway: + enabled: true + validate-on-migrate: true + servlet: + multipart: + max-file-size: 150MB + max-request-size: 160MB + threads: + virtual: + enabled: true + jackson: + default-property-inclusion: non_null + +server: + port: ${SERVER_PORT:8080} + servlet: + session: + cookie: + http-only: true + same-site: lax + secure: ${SESSION_COOKIE_SECURE:false} + +app: + data-root: ${APP_DATA_ROOT:file:../data} + deepseek-key-file: ${DEEPSEEK_KEY_FILE:./deepseek_key.txt} + dashscope-key-file: ${DASHSCOPE_KEY_FILE:./dashscope_key.txt} + master-key: ${APP_MASTER_KEY:smart-factory-local-master-key} + admin-username: ${APP_ADMIN_USERNAME:admin} + admin-password: ${APP_ADMIN_PASSWORD:admin123} + model-base-url: ${APP_MODEL_BASE_URL:https://api.deepseek.com} + model-id: ${APP_MODEL_ID:deepseek-v4-flash} + model-context-window: ${APP_MODEL_CONTEXT_WINDOW:131072} + sandbox-image: ${APP_SANDBOX_IMAGE:smart-factory-agent-runtime:0.1.0} + sandbox-network: ${APP_SANDBOX_NETWORK:bridge} + run-timeout: ${APP_RUN_TIMEOUT:60m} + +logging: + pattern: + level: "%5p [trace:%X{traceId:-}]" diff --git a/server/src/main/resources/db/migration/V1__initial_schema.sql b/server/src/main/resources/db/migration/V1__initial_schema.sql new file mode 100644 index 0000000..e8f89fd --- /dev/null +++ b/server/src/main/resources/db/migration/V1__initial_schema.sql @@ -0,0 +1,246 @@ +CREATE SCHEMA app; +CREATE SCHEMA agentscope; + +CREATE TABLE app.app_user ( + id UUID PRIMARY KEY, + username VARCHAR(64) NOT NULL UNIQUE, + password_hash VARCHAR(255) NOT NULL, + display_name VARCHAR(100) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + last_login_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE app.model_config ( + id UUID PRIMARY KEY, + name VARCHAR(100) NOT NULL UNIQUE, + provider VARCHAR(32) NOT NULL, + base_url VARCHAR(500) NOT NULL, + model_id VARCHAR(255) NOT NULL, + api_key_ciphertext BYTEA, + api_key_hint VARCHAR(16), + key_version SMALLINT, + config_json JSONB NOT NULL DEFAULT '{}'::jsonb, + capabilities_json JSONB NOT NULL DEFAULT '{}'::jsonb, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + is_default BOOLEAN NOT NULL DEFAULT FALSE, + created_by UUID REFERENCES app.app_user(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_model_provider CHECK (provider IN ('DASHSCOPE', 'OPENAI_COMPATIBLE')), + CONSTRAINT ck_model_key_pair CHECK ( + (api_key_ciphertext IS NULL AND key_version IS NULL) + OR (api_key_ciphertext IS NOT NULL AND key_version IS NOT NULL) + ), + CONSTRAINT ck_model_config_json CHECK (jsonb_typeof(config_json) = 'object'), + CONSTRAINT ck_model_capabilities_json CHECK (jsonb_typeof(capabilities_json) = 'object') +); + +CREATE UNIQUE INDEX uk_model_config_default ON app.model_config (is_default) WHERE is_default; + +CREATE TABLE app.model_assignment ( + role VARCHAR(32) PRIMARY KEY, + model_config_id UUID NOT NULL REFERENCES app.model_config(id), + assigned_by UUID REFERENCES app.app_user(id), + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_model_assignment_role CHECK (role IN ('ORCHESTRATION', 'WRITING', 'REVIEW')) +); + +CREATE INDEX ix_model_assignment_model ON app.model_assignment (model_config_id); + +CREATE TABLE app.project ( + id UUID PRIMARY KEY, + company_name VARCHAR(255) NOT NULL, + project_name VARCHAR(255) NOT NULL, + agui_thread_id VARCHAR(255) NOT NULL UNIQUE, + application_level VARCHAR(32) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'MATERIAL_CHECK', + created_by UUID NOT NULL REFERENCES app.app_user(id), + version BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_project_application_level CHECK (application_level IN ('ADVANCED', 'EXCELLENT')), + CONSTRAINT ck_project_status CHECK ( + status IN ('MATERIAL_CHECK', 'PLANNING', 'WRITING', 'DELIVERED', 'FAILED', 'ARCHIVED') + ), + CONSTRAINT ck_project_version CHECK (version >= 0) +); + +CREATE INDEX ix_project_updated_at ON app.project (updated_at DESC); + +CREATE TABLE app.project_file ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES app.project(id), + original_name VARCHAR(500) NOT NULL, + stored_name VARCHAR(255) NOT NULL, + relative_path VARCHAR(1000) NOT NULL, + mime_type VARCHAR(255) NOT NULL, + extension VARCHAR(32) NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 CHAR(64) NOT NULL, + status VARCHAR(24) NOT NULL DEFAULT 'READY', + uploaded_by UUID NOT NULL REFERENCES app.app_user(id), + deleted_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uk_project_file_path UNIQUE (project_id, relative_path), + CONSTRAINT ck_project_file_size CHECK (size_bytes >= 0), + CONSTRAINT ck_project_file_status CHECK (status IN ('UPLOADING', 'READY', 'FAILED', 'DELETED')), + CONSTRAINT ck_project_file_relative_path CHECK ( + relative_path <> '' + AND left(relative_path, 1) <> '/' + AND relative_path !~ '(^|/)\.\.(/|$)' + ) +); + +CREATE INDEX ix_project_file_project ON app.project_file (project_id, created_at DESC) + WHERE deleted_at IS NULL; + +CREATE TABLE app.project_plan ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES app.project(id), + plan_version INTEGER NOT NULL, + status VARCHAR(24) NOT NULL DEFAULT 'DRAFT', + plan_json JSONB NOT NULL, + created_by UUID NOT NULL REFERENCES app.app_user(id), + confirmed_by UUID REFERENCES app.app_user(id), + confirmed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uk_project_plan_version UNIQUE (project_id, plan_version), + CONSTRAINT ck_project_plan_version CHECK (plan_version > 0), + CONSTRAINT ck_project_plan_status CHECK (status IN ('DRAFT', 'CONFIRMED', 'SUPERSEDED')), + CONSTRAINT ck_project_plan_json CHECK (jsonb_typeof(plan_json) = 'object'), + CONSTRAINT ck_project_plan_confirmation CHECK ( + (status = 'CONFIRMED' AND confirmed_by IS NOT NULL AND confirmed_at IS NOT NULL) + OR (status <> 'CONFIRMED') + ) +); + +CREATE UNIQUE INDEX uk_project_plan_confirmed ON app.project_plan (project_id) + WHERE status = 'CONFIRMED'; + +CREATE TABLE app.agent_run ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES app.project(id), + parent_run_id UUID, + model_config_id UUID REFERENCES app.model_config(id), + trigger_type VARCHAR(24) NOT NULL, + status VARCHAR(24) NOT NULL, + pending_interrupt JSONB, + trace_id VARCHAR(100) NOT NULL, + error_code VARCHAR(100), + error_message TEXT, + started_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ended_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uk_agent_run_project UNIQUE (id, project_id), + CONSTRAINT fk_agent_run_parent_project + FOREIGN KEY (parent_run_id, project_id) REFERENCES app.agent_run(id, project_id), + CONSTRAINT ck_agent_run_trigger CHECK (trigger_type IN ('INITIAL', 'RESUME', 'RETRY')), + CONSTRAINT ck_agent_run_status CHECK ( + status IN ('RUNNING', 'WAITING_INPUT', 'COMPLETED', 'FAILED', 'CANCELLED', 'INTERRUPTED') + ), + CONSTRAINT ck_agent_run_pending_json CHECK ( + pending_interrupt IS NULL OR jsonb_typeof(pending_interrupt) = 'object' + ), + CONSTRAINT ck_agent_run_pending_status CHECK ( + (status = 'WAITING_INPUT' AND pending_interrupt IS NOT NULL) + OR (status <> 'WAITING_INPUT' AND pending_interrupt IS NULL) + ), + CONSTRAINT ck_agent_run_end CHECK ( + (status = 'RUNNING' AND ended_at IS NULL) + OR (status IN ('WAITING_INPUT', 'COMPLETED', 'FAILED', 'CANCELLED', 'INTERRUPTED') + AND ended_at IS NOT NULL) + ) +); + +CREATE INDEX ix_agent_run_project ON app.agent_run (project_id, started_at DESC); +CREATE UNIQUE INDEX uk_agent_run_active ON app.agent_run (project_id) + WHERE status IN ('RUNNING', 'WAITING_INPUT'); + +CREATE TABLE app.agent_event ( + id BIGSERIAL PRIMARY KEY, + project_id UUID NOT NULL REFERENCES app.project(id), + run_id UUID NOT NULL, + event_type VARCHAR(100) NOT NULL, + event_id VARCHAR(255), + payload JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_agent_event_run_project + FOREIGN KEY (run_id, project_id) REFERENCES app.agent_run(id, project_id), + CONSTRAINT ck_agent_event_payload CHECK (jsonb_typeof(payload) = 'object') +); + +CREATE INDEX ix_agent_event_project ON app.agent_event (project_id, id); +CREATE INDEX ix_agent_event_run ON app.agent_event (run_id, id); + +CREATE TABLE app.artifact ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES app.project(id), + run_id UUID, + kind VARCHAR(32) NOT NULL, + name VARCHAR(500) NOT NULL, + relative_path VARCHAR(1000) NOT NULL, + mime_type VARCHAR(255) NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 CHAR(64) NOT NULL, + metadata_json JSONB NOT NULL DEFAULT '{}'::jsonb, + published_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uk_artifact_path UNIQUE (project_id, relative_path), + CONSTRAINT fk_artifact_run_project + FOREIGN KEY (run_id, project_id) REFERENCES app.agent_run(id, project_id), + CONSTRAINT ck_artifact_kind CHECK (kind IN ('DOCX', 'PLANNING_REPORT', 'OTHER')), + CONSTRAINT ck_artifact_size CHECK (size_bytes > 0), + CONSTRAINT ck_artifact_metadata CHECK (jsonb_typeof(metadata_json) = 'object'), + CONSTRAINT ck_artifact_relative_path CHECK ( + relative_path <> '' + AND left(relative_path, 1) <> '/' + AND relative_path !~ '(^|/)\.\.(/|$)' + ) +); + +CREATE INDEX ix_artifact_project ON app.artifact (project_id, published_at DESC); + +CREATE TABLE agentscope.agentscope_skills ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL UNIQUE, + description TEXT NOT NULL, + skill_content TEXT NOT NULL, + source VARCHAR(255) NOT NULL, + metadata_json TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE agentscope.agentscope_skill_resources ( + id BIGINT NOT NULL REFERENCES agentscope.agentscope_skills(id) ON DELETE CASCADE, + resource_path VARCHAR(500) NOT NULL, + resource_content TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id, resource_path) +); + +CREATE TABLE app.skill_config ( + skill_name VARCHAR(255) PRIMARY KEY + REFERENCES agentscope.agentscope_skills(name) ON DELETE CASCADE, + version VARCHAR(64), + source_type VARCHAR(16) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + read_only BOOLEAN NOT NULL DEFAULT TRUE, + checksum CHAR(64) NOT NULL, + validation_status VARCHAR(16) NOT NULL DEFAULT 'VALID', + validation_message TEXT, + imported_by UUID REFERENCES app.app_user(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_skill_source_type CHECK (source_type IN ('BUILTIN', 'IMPORTED')), + CONSTRAINT ck_skill_validation_status CHECK (validation_status IN ('VALID', 'INVALID')), + CONSTRAINT ck_skill_read_only CHECK (source_type <> 'BUILTIN' OR read_only) +); + +CREATE INDEX ix_skill_config_enabled ON app.skill_config (enabled, skill_name) WHERE enabled; diff --git a/server/src/main/resources/prompts/smart-factory-agent-system.md b/server/src/main/resources/prompts/smart-factory-agent-system.md new file mode 100644 index 0000000..fbe9857 --- /dev/null +++ b/server/src/main/resources/prompts/smart-factory-agent-system.md @@ -0,0 +1,39 @@ +# 角色 + +你是智能工厂申报材料 Agent。你负责使用企业材料、百炼知识库、已启用 Skills 和项目工作区,形成建设规划、申报书审阅稿和评审结果。 + +# 语言 + +默认使用简体中文进行用户可见回复、执行说明、事实台账、建设规划和申报书编写。仅代码、命令、文件路径、标准原文、产品型号及无法准确翻译的专有名词保留原语言;用户明确要求其他语言时才切换。 + +# 事实与规划边界 + +- C:企业材料或用户确认的企业事实。材料已经覆盖的字段必须忠实使用,不得改写、美化或用案例替换。 +- E:企业公开资料,必须保留来源并标记待企业确认。 +- R:政策、标准、行业方法和同行案例,只用于支撑规划。 +- P:基于 R 形成的未来规划、建议目标和测算假设。规划确认后成为全书统一基线。 +- U:缺失、冲突或无法核实的企业现状,写为待企业确认并进入 DOCX 原生批注。 +- C/E/R/P/U 仅用于内部事实台账,不得出现在面向用户的 DOCX;统一转换为“已确认 / 待核实 / 待确认”等可读口径。 + +材料未覆盖的建设内容,应主动形成具体、完整、可执行的 P。自由生成仅限未来规划,不得编造企业当前设备、系统、营收、能耗、认证和既有成效。 +未知企业现状必须使用“需确认是否……”“待企业提供……”等非断言句式。严禁先写成已发生、已具备或已承诺的肯定事实,再在句尾附“待确认”;真实性承诺也只能写为待签署或待提供。 + +# 自主执行 + +1. 先递归查看 `inputs/`,保留并利用上传目录、原文件名和材料分类之间的语义关系;同名文件必须结合完整相对路径判断来源。 +2. 主动选择与文件类型相符的 PDF、PPTX、XLS/XLSX、DOCX 等文档 Skill,先读取 Skill 的完整 `SKILL.md`,再按其方法做结构化读取。不得只凭文件名推断正文。 +3. `document_view` 是按需视觉补充工具,不是默认步骤。仅当文档 Skill 提取结果明显不足、页面为扫描件,或 PDF/PPT/工作表的图示、布局、截图对判断重要时,才使用自身视觉能力查看实际页面。由你决定页码、幻灯片、工作表与范围;建议每次最多渲染 5 张,可分批调用。大型工作表应主动拆分 range 查看,无需模拟滚动。 +4. 判断输入与事实充分程度,主动检索知识库并选择必要业务 Skill。 +5. 先读企业材料,再用知识库补充政策、标准、行业方法和规划依据。缺少企业现状时保持未知,不得让知识库或同行案例冒充企业事实。 +6. 将事实写入 work/facts,将规划锚点写入 work/plans,将引用写入 references。 + 材料检验阶段生成 `work/facts/material-check.json`;规划阶段生成 `work/plans/proposed-plan.json`。 + 两者必须来自当前企业材料与本次知识库分析,不得套用固定企业方案。 + 阶段任务指定的结构化文件是必需产物。获得最小事实后应先写入合法初稿,再随分析持续更新;不得把必需产物推迟到全部可选读取和视觉检查之后。 +7. 规划确认后保持名称、架构、场景、KPI、投资、周期和术语前后一致。 +8. 常规工作区读写、搜索和 Shell 可自主执行;所有操作限定在 Docker 工作区内。不得探测宿主机、读取凭证、修改系统配置或访问与任务无关的网络服务;知识库访问只通过已启用的 RAG Skill。 +9. 工具返回失败、非零退出码、参数错误或文件冲突时,将错误结果视为可诊断观察;分析原因,修正参数、路径或前置条件后重试,也可选择替代工具。单个工具失败不得直接结束 Run。只有安全策略拒绝、用户停止、模型重连耗尽或确认无可恢复路径时才终止,且不得返回假成功。 +10. 页面输出只保留业务结论、待确认事项和必要依据。不要汇报后台 JSON、内部相对或绝对路径、编码或 Markdown 格式、命令、Skill 名称、工具调用、校验过程,以及“已写入”“已保存到某文件”等内部执行细节;这些操作由执行信息流单独展示。 + +# 完成条件 + +只有规划已确认、事实与规划口径一致、未知企业事实已转为批注、DOCX 通过打开与结构校验后,才可发布产物。申报书正文目标为 1 万至 2 万汉字,应完整展开建设背景、现状与差距、总体架构、建设场景、数据与系统集成、实施路径、投资与效益、保障机制等内容。关键未知企业事实允许待确认;能够由标准、知识库、Skill 和已确认规划形成的未来场景、技术路径、阶段任务与建议指标必须充分写实,不得用批注或空泛表述代替正文。不得把 Markdown 表格分隔行写入 Word 表格。中文字体须使用英文族名 `SimSun`(正文)与 `SimHei`(标题),同一文本运行的 ascii、hAnsi 与 eastAsia 均须使用对应字体,避免跨平台渲染为方框。当前不要求生成目录,不要创建仅含 TOC 域且需要办公软件手动更新的空目录;须检查表格换行、页码与批注锚点。每个 Word 原生批注 ID 只能锚定一处,正文中对应的 commentRangeStart、commentRangeEnd、commentReference 必须各出现且仅出现一次;同一待确认问题若在多处出现,必须复制批注正文并为每处使用新的唯一 ID。 diff --git a/server/src/main/resources/prompts/smart-factory-compaction.md b/server/src/main/resources/prompts/smart-factory-compaction.md new file mode 100644 index 0000000..cc47cac --- /dev/null +++ b/server/src/main/resources/prompts/smart-factory-compaction.md @@ -0,0 +1,9 @@ +请将当前会话压缩为可继续执行的结构化工作记忆。必须保留: + +1. 企业名称、申报等级,以及 C(已确认事实)、E(外部依据)、R(规划建议)、P(待实施)、U(待确认)边界。 +2. 已确认并冻结的建设规划,包括建设方向、场景、KPI、投资区间、建设周期和版本。 +3. 材料之间的冲突、全部未解决 U 项、Word 批注要求和事实约束。 +4. 已调用 Skill、关键工具结果、已生成或已修改的工作区文件及其校验状态。 +5. 当前任务进度、失败原因、尚未完成的动作和最安全的下一步。 + +不得把知识库内容改写为企业事实,不得把规划建议改写为已建成现状。省略寒暄、重复过程和可从工作区重新读取的大段工具输出。 diff --git a/server/src/test/java/cn/alphaline/smartfactory/DatabaseAndEventIntegrationTest.java b/server/src/test/java/cn/alphaline/smartfactory/DatabaseAndEventIntegrationTest.java new file mode 100644 index 0000000..9650fe1 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/DatabaseAndEventIntegrationTest.java @@ -0,0 +1,238 @@ +package cn.alphaline.smartfactory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import cn.alphaline.smartfactory.agent.AgentEventService; +import cn.alphaline.smartfactory.artifact.ArtifactService; +import cn.alphaline.smartfactory.artifact.DocxValidator; +import cn.alphaline.smartfactory.project.ProjectService; +import cn.alphaline.smartfactory.project.ProjectFileService; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.DriverManager; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.ds.PGSimpleDataSource; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * 验证 PostgreSQL 17 全量迁移及事件游标回放。 + */ +@Testcontainers +class DatabaseAndEventIntegrationTest { + + @Container + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:17-alpine"); + + @TempDir + private Path temporaryDirectory; + + /** + * 在干净 PostgreSQL 17 实例执行并校验全部 Flyway 迁移。 + */ + @BeforeAll + static void migrate() { + Flyway flyway = Flyway.configure() + .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) + .locations("classpath:db/migration") + .load(); + flyway.migrate(); + flyway.validate(); + assertThat(flyway.migrate().migrationsExecuted).isZero(); + } + + /** + * 验证核心表、索引和约束已建立。 + * + * @throws Exception 数据库访问失败时抛出 + */ + @Test + void shouldCreateCoreSchemaOnPostgres17() throws Exception { + try (var connection = DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + var statement = connection.createStatement(); + var result = statement.executeQuery(""" + SELECT count(*) FROM information_schema.tables + WHERE table_schema IN ('app', 'agentscope') + """)) { + assertThat(result.next()).isTrue(); + assertThat(result.getInt(1)).isEqualTo(12); + } + } + + /** + * 验证事件按项目全局 ID 增量回放且不重复。 + */ + @Test + void shouldReplayEventsAfterCursorInOrder() { + JdbcClient jdbc = jdbc(); + UUID userId = UUID.randomUUID(); + UUID modelId = UUID.randomUUID(); + UUID projectId = UUID.randomUUID(); + UUID runId = UUID.randomUUID(); + jdbc.sql("INSERT INTO app.app_user(id, username, password_hash, display_name) VALUES (:id, :name, 'x', 'test')") + .param("id", userId).param("name", "u-" + userId).update(); + jdbc.sql(""" + INSERT INTO app.model_config(id, name, provider, base_url, model_id, is_default) + VALUES (:id, :name, 'OPENAI_COMPATIBLE', 'https://example.test', 'model', TRUE) + """).param("id", modelId).param("name", "m-" + modelId).update(); + jdbc.sql(""" + INSERT INTO app.project(id, company_name, project_name, agui_thread_id, application_level, created_by) + VALUES (:id, '企业', '项目', :thread, 'ADVANCED', :userId) + """).param("id", projectId).param("thread", "t-" + projectId).param("userId", userId).update(); + jdbc.sql(""" + INSERT INTO app.agent_run(id, project_id, model_config_id, trigger_type, status, trace_id) + VALUES (:id, :projectId, :modelId, 'INITIAL', 'RUNNING', :trace) + """).param("id", runId).param("projectId", projectId).param("modelId", modelId) + .param("trace", UUID.randomUUID().toString()).update(); + + AgentEventService service = new AgentEventService(jdbc, new ObjectMapper()); + long first = service.append(projectId, runId, "RUN_STARTED", Map.of("phase", "MATERIAL_CHECK")).id(); + long second = service.append(projectId, runId, "TEXT_MESSAGE_CONTENT", Map.of("delta", "分析")).id(); + long third = service.append(projectId, runId, "TEXT_MESSAGE_CONTENT", Map.of("delta", "完成")).id(); + + assertThat(service.listAfter(projectId, first, 100)) + .extracting(AgentEventService.EventView::id) + .containsExactly(second, third); + + var next = service.streamAfter(projectId, third) + .filter(event -> !"HEARTBEAT".equals(event.type())) + .next() + .toFuture(); + long pushed = service.append(projectId, runId, "TEXT_MESSAGE_CONTENT", Map.of("delta", "推送")).id(); + assertThat(next.orTimeout(2, TimeUnit.SECONDS).join().id()).isEqualTo(pushed); + } + + /** + * 验证重试生成同一路径产物时更新登记信息,避免唯一约束导致成功 Run 被标记失败。 + * + * @throws Exception 临时文件写入失败时抛出 + */ + @Test + void shouldReplaceArtifactMetadataForSameProjectPath() throws Exception { + JdbcClient jdbc = jdbc(); + UUID userId = UUID.randomUUID(); + UUID modelId = UUID.randomUUID(); + UUID projectId = UUID.randomUUID(); + UUID firstRunId = UUID.randomUUID(); + UUID secondRunId = UUID.randomUUID(); + jdbc.sql("INSERT INTO app.app_user(id, username, password_hash, display_name) VALUES (:id, :name, 'x', 'test')") + .param("id", userId).param("name", "u-" + userId).update(); + jdbc.sql(""" + INSERT INTO app.model_config(id, name, provider, base_url, model_id) + VALUES (:id, :name, 'OPENAI_COMPATIBLE', 'https://example.test', 'model') + """).param("id", modelId).param("name", "m-" + modelId).update(); + jdbc.sql(""" + INSERT INTO app.project(id, company_name, project_name, agui_thread_id, application_level, created_by) + VALUES (:id, '企业', '项目', :thread, 'ADVANCED', :userId) + """).param("id", projectId).param("thread", "t-" + projectId).param("userId", userId).update(); + for (UUID runId : List.of(firstRunId, secondRunId)) { + jdbc.sql(""" + INSERT INTO app.agent_run( + id, project_id, model_config_id, trigger_type, status, trace_id, ended_at) + VALUES (:id, :projectId, :modelId, 'RETRY', 'COMPLETED', :trace, CURRENT_TIMESTAMP) + """).param("id", runId).param("projectId", projectId).param("modelId", modelId) + .param("trace", UUID.randomUUID().toString()).update(); + } + + Path document = temporaryDirectory.resolve("draft.docx"); + Files.writeString(document, "first"); + ProjectFileService files = mock(ProjectFileService.class); + when(files.safeProjectPath(projectId, "artifacts/draft.docx")).thenReturn(document); + ArtifactService artifacts = new ArtifactService(jdbc, files, new DocxValidator()); + ObjectMapper mapper = new ObjectMapper(); + + ArtifactService.ArtifactView first = artifacts.publish( + projectId, firstRunId, "DOCX", "draft.docx", "artifacts/draft.docx", + mapper.createObjectNode().put("version", 1)); + Files.writeString(document, "second version"); + ArtifactService.ArtifactView second = artifacts.publish( + projectId, secondRunId, "DOCX", "draft.docx", "artifacts/draft.docx", + mapper.createObjectNode().put("version", 2)); + + assertThat(second.id()).isEqualTo(first.id()); + assertThat(second.runId()).isEqualTo(secondRunId); + assertThat(second.sizeBytes()).isEqualTo(Files.size(document)); + assertThat(artifacts.list(projectId)).hasSize(1); + } + + /** + * 验证项目真删除会清除所有关联业务记录。 + */ + @Test + void shouldDeleteProjectRecords() { + JdbcClient jdbc = jdbc(); + UUID userId = UUID.randomUUID(); + UUID projectId = UUID.randomUUID(); + UUID runId = UUID.randomUUID(); + jdbc.sql("INSERT INTO app.app_user(id, username, password_hash, display_name) VALUES (:id, :name, 'x', 'test')") + .param("id", userId).param("name", "u-" + userId).update(); + jdbc.sql(""" + INSERT INTO app.project(id, company_name, project_name, agui_thread_id, application_level, created_by) + VALUES (:id, '待删除企业', '待删除项目', :thread, 'ADVANCED', :userId) + """).param("id", projectId).param("thread", "t-" + projectId).param("userId", userId).update(); + jdbc.sql(""" + INSERT INTO app.agent_run(id, project_id, trigger_type, status, trace_id, ended_at) + VALUES (:id, :projectId, 'INITIAL', 'COMPLETED', :trace, CURRENT_TIMESTAMP) + """).param("id", runId).param("projectId", projectId) + .param("trace", UUID.randomUUID().toString()).update(); + jdbc.sql(""" + INSERT INTO app.agent_event(project_id, run_id, event_type, payload) + VALUES (:projectId, :runId, 'RUN_FINISHED', '{}'::jsonb) + """).param("projectId", projectId).param("runId", runId).update(); + jdbc.sql(""" + INSERT INTO app.project_plan(id, project_id, plan_version, status, plan_json, created_by) + VALUES (:id, :projectId, 1, 'DRAFT', '{}'::jsonb, :userId) + """).param("id", UUID.randomUUID()).param("projectId", projectId).param("userId", userId).update(); + jdbc.sql(""" + INSERT INTO app.project_file( + id, project_id, original_name, stored_name, relative_path, mime_type, + extension, size_bytes, sha256, uploaded_by) + VALUES (:id, :projectId, 'input.txt', 'input.txt', 'inputs/input.txt', + 'text/plain', 'txt', 1, :sha, :userId) + """).param("id", UUID.randomUUID()).param("projectId", projectId) + .param("sha", "0".repeat(64)).param("userId", userId).update(); + jdbc.sql(""" + INSERT INTO app.artifact( + id, project_id, run_id, kind, name, relative_path, mime_type, size_bytes, sha256) + VALUES (:id, :projectId, :runId, 'OTHER', 'result.txt', 'artifacts/result.txt', + 'text/plain', 1, :sha) + """).param("id", UUID.randomUUID()).param("projectId", projectId).param("runId", runId) + .param("sha", "0".repeat(64)).update(); + + ProjectService service = new ProjectService(jdbc, mock(cn.alphaline.smartfactory.auth.UserService.class), new ObjectMapper()); + service.delete(projectId); + + for (String table : List.of("agent_event", "artifact", "project_plan", "project_file", "agent_run")) { + Long count = jdbc.sql("SELECT COUNT(*) FROM app." + table + " WHERE project_id = :projectId") + .param("projectId", projectId) + .query(Long.class) + .single(); + assertThat(count).as(table).isZero(); + } + assertThat(jdbc.sql("SELECT COUNT(*) FROM app.project WHERE id = :projectId") + .param("projectId", projectId) + .query(Long.class) + .single()).isZero(); + } + + private JdbcClient jdbc() { + PGSimpleDataSource source = new PGSimpleDataSource(); + source.setURL(POSTGRES.getJdbcUrl()); + source.setUser(POSTGRES.getUsername()); + source.setPassword(POSTGRES.getPassword()); + return JdbcClient.create(source); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/KeyCipherAndShellTest.java b/server/src/test/java/cn/alphaline/smartfactory/KeyCipherAndShellTest.java new file mode 100644 index 0000000..8791d6e --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/KeyCipherAndShellTest.java @@ -0,0 +1,35 @@ +package cn.alphaline.smartfactory; + +import static org.assertj.core.api.Assertions.assertThat; + +import cn.alphaline.smartfactory.config.AppProperties; +import cn.alphaline.smartfactory.model.KeyCipher; +import java.nio.file.Path; +import java.time.Duration; +import org.junit.jupiter.api.Test; + +/** + * 验证模型密钥保护。 + */ +class KeyCipherAndShellTest { + + /** + * 验证密钥可恢复且相同明文每次产生不同密文。 + */ + @Test + void shouldEncryptModelKeyWithRandomIv() { + KeyCipher cipher = new KeyCipher(properties()); + byte[] first = cipher.encrypt("local-test-key"); + byte[] second = cipher.encrypt("local-test-key"); + + assertThat(first).isNotEqualTo(second); + assertThat(cipher.decrypt(first)).isEqualTo("local-test-key"); + } + + private AppProperties properties() { + return new AppProperties( + Path.of("data"), Path.of("deepseek"), Path.of("dashscope"), + "unit-test-master", "admin", "admin123", "https://api.example.test", "model", + 131_072, "smart-factory-agent-runtime:test", "bridge", Duration.ofMinutes(1)); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/agent/AgentExecutionServiceTest.java b/server/src/test/java/cn/alphaline/smartfactory/agent/AgentExecutionServiceTest.java new file mode 100644 index 0000000..cf3e17e --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/agent/AgentExecutionServiceTest.java @@ -0,0 +1,27 @@ +package cn.alphaline.smartfactory.agent; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +/** + * 验证 Agent 事件持久化的精简规则。 + */ +class AgentExecutionServiceTest { + + /** + * 验证文档视觉结果保留图片路径元数据并丢弃 Base64 正文。 + */ + @Test + void shouldStripInlineImageDataFromPersistedToolResult() { + String content = """ + document_view_result={"images":[{"path":"work/tmp/document-view/a/render-1.png"}]} + {"type":"image","source":{"media_type":"image/png","data":"very-large-base64"}} + """; + + String result = AgentExecutionService.stripInlineImageData(content); + + assertThat(result).contains("render-1.png"); + assertThat(result).doesNotContain("very-large-base64"); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/agent/AgentRunServiceTest.java b/server/src/test/java/cn/alphaline/smartfactory/agent/AgentRunServiceTest.java new file mode 100644 index 0000000..ecc4717 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/agent/AgentRunServiceTest.java @@ -0,0 +1,81 @@ +package cn.alphaline.smartfactory.agent; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.agentscope.core.model.transport.HttpTransportException; +import io.agentscope.core.skill.AgentSkill; +import java.nio.file.Path; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * 验证 Agent Run 的模型重连边界。 + */ +class AgentRunServiceTest { + + /** + * 网络故障和服务端错误允许重连,参数错误保持原始失败。 + */ + @Test + void shouldRetryOnlyRecoverableModelFailures() { + assertThat(AgentExecutionService.MAX_MODEL_RECONNECTS).isEqualTo(5); + assertThat(AgentExecutionService.isRetryableModelFailure( + new RuntimeException(new HttpTransportException("disconnected")))).isTrue(); + assertThat(AgentExecutionService.isRetryableModelFailure( + new HttpTransportException("unavailable", 503, ""))).isTrue(); + assertThat(AgentExecutionService.isRetryableModelFailure( + new HttpTransportException("invalid request", 400, ""))).isFalse(); + assertThat(AgentExecutionService.isRetryableModelFailure( + new IllegalArgumentException("invalid prompt"))).isFalse(); + } + + /** + * 验证上下文压缩只按模型窗口 90% Token 触发。 + */ + @Test + void shouldCompactAtNinetyPercentTokensOnly() { + var config = AgentFactory.compactionFor(100_000, "summary"); + + assertThat(config.getTriggerTokens()).isEqualTo(90_000); + assertThat(config.getTriggerMessages()).isZero(); + assertThat(config.getSummaryPrompt()).isEqualTo("summary"); + } + + /** + * 验证 Agent 调用 Skill 时使用无来源后缀的名称,并完整保留仓库信息。 + */ + @Test + void shouldExposeCanonicalSkillIdWithoutLosingSkillInformation() { + AgentSkill source = new AgentSkill( + Map.of("name", "pdf", "description", "读取 PDF", "version", "1.0"), + "使用说明", + Map.of("references/guide.md", "参考内容"), + "imported", + Path.of("/skills/pdf")); + + AgentSkill canonical = AgentFactory.canonicalSkill(source); + + assertThat(canonical.getSkillId()).isEqualTo("pdf"); + assertThat(canonical.getMetadata()).isEqualTo(source.getMetadata()); + assertThat(canonical.getSkillContent()).isEqualTo(source.getSkillContent()); + assertThat(canonical.getResources()).isEqualTo(source.getResources()); + assertThat(canonical.getSource()).isEqualTo("imported"); + assertThat(canonical.getOriginDir()).isEqualTo(source.getOriginDir()); + } + + /** + * 验证模型输出年份数组时可归一化为前端和确认接口使用的规划年数。 + */ + @Test + void shouldNormalizePlanningYearArray() { + ObjectNode plan = new ObjectMapper().createObjectNode(); + plan.putArray("planningYears").add("2026").add("2027"); + + AgentOutputService.normalizePlanningYears(plan); + + assertThat(plan.path("planningYears").asInt()).isEqualTo(2); + assertThat(plan.path("planningPeriod").asText()).isEqualTo("2026-2027"); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/agent/DocumentViewToolTest.java b/server/src/test/java/cn/alphaline/smartfactory/agent/DocumentViewToolTest.java new file mode 100644 index 0000000..f9eedeb --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/agent/DocumentViewToolTest.java @@ -0,0 +1,28 @@ +package cn.alphaline.smartfactory.agent; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.agentscope.core.model.ToolSchema; +import io.agentscope.core.tool.Toolkit; +import org.junit.jupiter.api.Test; + +/** + * 验证文档视觉工具可以被 AgentScope 注册并暴露结构化参数。 + */ +class DocumentViewToolTest { + + /** + * 验证多视图参数能够进入模型工具定义。 + */ + @Test + void shouldRegisterMultiViewSchema() { + Toolkit toolkit = new Toolkit(); + + toolkit.registerTool(new DocumentViewTool(new ObjectMapper())); + + ToolSchema schema = toolkit.getToolSchemas().getFirst(); + assertThat(schema.getName()).isEqualTo("document_view"); + assertThat(schema.getParameters().toString()).contains("views", "path", "page", "sheet", "range"); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/agent/PagedReadFileToolTest.java b/server/src/test/java/cn/alphaline/smartfactory/agent/PagedReadFileToolTest.java new file mode 100644 index 0000000..d1aeb2c --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/agent/PagedReadFileToolTest.java @@ -0,0 +1,66 @@ +package cn.alphaline.smartfactory.agent; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.harness.agent.filesystem.model.ExecuteResponse; +import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem; +import io.agentscope.harness.agent.workspace.WorkspacePathNormalizer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import org.junit.jupiter.api.Test; + +/** + * 验证文件读取工具不会静默丢失后续内容。 + */ +class PagedReadFileToolTest { + + /** + * 沙箱返回分页元数据时,应将下一页位置明确告知 Agent。 + */ + @Test + void shouldTellAgentHowToContinueReading() { + AbstractSandboxFilesystem filesystem = mock(AbstractSandboxFilesystem.class); + String content = Base64.getEncoder().encodeToString("第一行\n第二行".getBytes(StandardCharsets.UTF_8)); + when(filesystem.execute(any(RuntimeContext.class), anyString(), isNull())) + .thenReturn(new ExecuteResponse( + "{\"ok\":true,\"truncated\":true,\"nextOffset\":2,\"returnedLines\":2,\"lineTooLong\":false}\n" + + content, + 0, + false)); + PagedReadFileTool tool = new PagedReadFileTool( + filesystem, WorkspacePathNormalizer.of("/workspace"), new ObjectMapper()); + + String result = tool.readFile(RuntimeContext.empty(), "/workspace/work/report.txt", 0, 2); + + assertThat(result).contains("第一行\n第二行"); + assertThat(result).contains("内容未读完"); + assertThat(result).contains("offset=2"); + } + + /** + * 沙箱自身发生截断时,应明确提示重试,不能把残缺内容当作完整结果。 + */ + @Test + void shouldExposeUnexpectedSandboxTruncation() { + AbstractSandboxFilesystem filesystem = mock(AbstractSandboxFilesystem.class); + when(filesystem.execute(any(RuntimeContext.class), anyString(), isNull())) + .thenReturn(new ExecuteResponse( + "{\"ok\":true,\"truncated\":true,\"nextOffset\":10,\"returnedLines\":10,\"lineTooLong\":false}\n", + 0, + true)); + PagedReadFileTool tool = new PagedReadFileTool( + filesystem, WorkspacePathNormalizer.of("/workspace"), new ObjectMapper()); + + String result = tool.readFile(RuntimeContext.empty(), "work/report.txt", 0, 10); + + assertThat(result).contains("内容未读完"); + assertThat(result).contains("offset=10"); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/artifact/DocxValidatorTest.java b/server/src/test/java/cn/alphaline/smartfactory/artifact/DocxValidatorTest.java new file mode 100644 index 0000000..8284d14 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/artifact/DocxValidatorTest.java @@ -0,0 +1,125 @@ +package cn.alphaline.smartfactory.artifact; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import cn.alphaline.smartfactory.common.ApiException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * 验证 DOCX 发布边界会拒绝伪装文件和批注错锚。 + */ +class DocxValidatorTest { + + private final DocxValidator validator = new DocxValidator(); + + /** + * 验证最小有效 Word 文档可通过结构校验。 + * + * @param directory 临时目录 + * @throws IOException DOCX 写入失败时抛出 + */ + @Test + void shouldValidateMinimalDocx(@TempDir Path directory) throws IOException { + Path docx = writeDocx(directory.resolve("valid.docx"), Map.of()); + + DocxValidator.ValidationResult result = validator.validate(docx); + + assertThat(result.entryCount()).isEqualTo(3); + assertThat(result.commentCount()).isZero(); + } + + /** + * 验证批注锚点与批注定义不一致时拒绝发布。 + * + * @param directory 临时目录 + * @throws IOException DOCX 写入失败时抛出 + */ + @Test + void shouldRejectBrokenCommentAnchor(@TempDir Path directory) throws IOException { + Map extras = new LinkedHashMap<>(); + extras.put("word/comments.xml", """ + + + 待确认 + + """); + extras.put("word/_rels/document.xml.rels", """ + + + + + """); + Path docx = writeDocx(directory.resolve("broken.docx"), extras); + + assertThatThrownBy(() -> validator.validate(docx)) + .isInstanceOf(ApiException.class) + .hasMessageContaining("批注"); + } + + /** + * 验证同一批注编号存在多个正文锚点时拒绝发布。 + * + * @param directory 临时目录 + * @throws IOException DOCX 写入失败时抛出 + */ + @Test + void shouldRejectDuplicateCommentAnchor(@TempDir Path directory) throws IOException { + Map extras = new LinkedHashMap<>(); + extras.put("word/document.xml", """ + + + + 待确认 + + + + """); + extras.put("word/comments.xml", """ + + + 待确认 + + """); + extras.put("word/_rels/document.xml.rels", """ + + + + + """); + + assertThatThrownBy(() -> validator.validate(writeDocx(directory.resolve("duplicate.docx"), extras))) + .isInstanceOf(ApiException.class) + .hasMessageContaining("重复"); + } + + private Path writeDocx(Path path, Map extras) throws IOException { + Map entries = new LinkedHashMap<>(); + entries.put("[Content_Types].xml", ""); + entries.put("_rels/.rels", ""); + entries.put("word/document.xml", """ + + + 智能工厂申报书 + + """); + entries.putAll(extras); + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(path))) { + for (Map.Entry entry : entries.entrySet()) { + zip.putNextEntry(new ZipEntry(entry.getKey())); + zip.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + } + return path; + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/auth/AuthControllerTest.java b/server/src/test/java/cn/alphaline/smartfactory/auth/AuthControllerTest.java new file mode 100644 index 0000000..29e7bb2 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/auth/AuthControllerTest.java @@ -0,0 +1,43 @@ +package cn.alphaline.smartfactory.auth; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import cn.alphaline.smartfactory.common.GlobalExceptionHandler; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * 验证登录边界返回稳定的认证错误码。 + */ +class AuthControllerTest { + + /** + * 验证错误密码返回 401,且不会落入 500 兜底。 + * + * @throws Exception MockMvc 执行失败时抛出 + */ + @Test + void shouldReturnUnauthorizedForWrongPassword() throws Exception { + AuthenticationManager manager = mock(AuthenticationManager.class); + when(manager.authenticate(any())).thenThrow(new BadCredentialsException("bad credentials")); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new AuthController(manager)) + .setControllerAdvice(new GlobalExceptionHandler()) + .build(); + + mvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"admin\",\"password\":\"wrong-password\"}")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.code").value("AUTHENTICATION_FAILED")) + .andExpect(jsonPath("$.message").value("用户名或密码错误")); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/common/GlobalExceptionHandlerTest.java b/server/src/test/java/cn/alphaline/smartfactory/common/GlobalExceptionHandlerTest.java new file mode 100644 index 0000000..08c0034 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/common/GlobalExceptionHandlerTest.java @@ -0,0 +1,24 @@ +package cn.alphaline.smartfactory.common; + +import static org.assertj.core.api.Assertions.assertThatCode; + +import org.junit.jupiter.api.Test; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; + +/** + * 验证统一异常边界对流式连接终止的处理。 + */ +class GlobalExceptionHandlerTest { + + /** + * 客户端断开已提交的流式响应时不再尝试写入 JSON 错误体。 + */ + @Test + void shouldIgnoreExpectedStreamDisconnect() { + GlobalExceptionHandler handler = new GlobalExceptionHandler(); + + assertThatCode(() -> handler.handleClientDisconnect( + new AsyncRequestNotUsableException("ServletOutputStream failed to flush"))) + .doesNotThrowAnyException(); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/project/ProjectFileServiceTest.java b/server/src/test/java/cn/alphaline/smartfactory/project/ProjectFileServiceTest.java new file mode 100644 index 0000000..0524160 --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/project/ProjectFileServiceTest.java @@ -0,0 +1,87 @@ +package cn.alphaline.smartfactory.project; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import cn.alphaline.smartfactory.auth.UserService; +import cn.alphaline.smartfactory.config.AppProperties; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.core.simple.JdbcClient; + +/** + * 验证项目工作区文件操作。 + */ +class ProjectFileServiceTest { + + @TempDir + private Path temporaryDirectory; + + /** + * 验证删除项目时会递归删除其受控工作区。 + * + * @throws Exception 测试文件创建失败时抛出 + */ + @Test + void shouldDeleteProjectWorkspace() throws Exception { + AppProperties properties = new AppProperties( + temporaryDirectory, Path.of("deepseek"), Path.of("dashscope"), + "test-master", "admin", "admin", "https://example.test", "model", + 131_072, "runtime:test", "bridge", Duration.ofMinutes(1)); + ProjectFileService service = new ProjectFileService( + mock(JdbcClient.class), mock(UserService.class), mock(ProjectService.class), properties); + UUID projectId = UUID.randomUUID(); + Path file = service.projectRoot(projectId).resolve("inputs/company.txt"); + Files.createDirectories(file.getParent()); + Files.writeString(file, "企业材料"); + + service.deleteWorkspace(projectId); + + assertThat(service.projectRoot(projectId)).doesNotExist(); + } + + /** + * 验证上传路径保留文件夹与原文件名。 + */ + @Test + void shouldPreserveUploadedFolderPath() { + ProjectFileService service = service(); + + assertThat(service.normalizeUploadPath("测试输入/场景一/设备清单.xlsx", "设备清单.xlsx")) + .isEqualTo("inputs/测试输入/场景一/设备清单.xlsx"); + assertThat(service.normalizeUploadPath(null, "企业材料.pdf")) + .isEqualTo("inputs/企业材料.pdf"); + } + + /** + * 验证上传路径不能越出 inputs 工作区。 + */ + @Test + void shouldRejectUnsafeFolderPath() { + ProjectFileService service = service(); + + assertThatThrownBy(() -> service.normalizeUploadPath("../企业材料.pdf", "企业材料.pdf")) + .isInstanceOf(cn.alphaline.smartfactory.common.ApiException.class); + assertThatThrownBy(() -> service.normalizeUploadPath("其他文件.pdf", "企业材料.pdf")) + .isInstanceOf(cn.alphaline.smartfactory.common.ApiException.class); + } + + /** + * 创建使用临时数据目录的文件服务。 + * + * @return 文件服务 + */ + private ProjectFileService service() { + AppProperties properties = new AppProperties( + temporaryDirectory, Path.of("deepseek"), Path.of("dashscope"), + "test-master", "admin", "admin", "https://example.test", "model", + 131_072, "runtime:test", "bridge", Duration.ofMinutes(1)); + return new ProjectFileService( + mock(JdbcClient.class), mock(UserService.class), mock(ProjectService.class), properties); + } +} diff --git a/server/src/test/java/cn/alphaline/smartfactory/skill/SkillArchiveTest.java b/server/src/test/java/cn/alphaline/smartfactory/skill/SkillArchiveTest.java new file mode 100644 index 0000000..14e814f --- /dev/null +++ b/server/src/test/java/cn/alphaline/smartfactory/skill/SkillArchiveTest.java @@ -0,0 +1,73 @@ +package cn.alphaline.smartfactory.skill; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockMultipartFile; + +/** + * 验证 Skill ZIP 的目录识别与无关文件过滤。 + */ +class SkillArchiveTest { + + @TempDir + private Path temporaryDirectory; + + /** + * 验证 macOS 元数据与 Python 缓存不会阻止有效 Skill 导入。 + * + * @throws Exception ZIP 构造或解压失败时抛出 + */ + @Test + void shouldLocateSkillAndIgnoreGeneratedFiles() throws Exception { + Map files = new LinkedHashMap<>(); + files.put("sample/SKILL.md", "---\nname: sample\ndescription: 示例 Skill\n---\n规则".getBytes(StandardCharsets.UTF_8)); + files.put("sample/scripts/run.py", "print('ok')".getBytes(StandardCharsets.UTF_8)); + files.put("__MACOSX/._sample", new byte[]{0, 1}); + files.put("sample/.DS_Store", new byte[]{0, 1}); + files.put("sample/scripts/__pycache__/run.pyc", new byte[]{0, 1}); + + MockMultipartFile archive = new MockMultipartFile( + "file", "sample.zip", "application/zip", zip(files)); + Path extracted = temporaryDirectory.resolve("extracted"); + Files.createDirectories(extracted); + + SkillService.unzip(archive, extracted); + Path skillRoot = SkillService.locateSkillRoot(extracted); + SkillPackageReader.SkillPackage skillPackage = new SkillPackageReader().read(skillRoot, "imported"); + + assertThat(skillRoot.getFileName().toString()).isEqualTo("sample"); + assertThat(skillPackage.skill().getName()).isEqualTo("sample"); + assertThat(skillPackage.skill().getResourcePaths()).containsExactly("scripts/run.py"); + assertThat(extracted.resolve("__MACOSX")).doesNotExist(); + assertThat(skillRoot.resolve("scripts/__pycache__")).doesNotExist(); + } + + /** + * 构造测试 ZIP。 + * + * @param files ZIP 内文件 + * @return ZIP 字节 + * @throws Exception ZIP 写入失败时抛出 + */ + private byte[] zip(Map files) throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(output, StandardCharsets.UTF_8)) { + for (Map.Entry file : files.entrySet()) { + zip.putNextEntry(new ZipEntry(file.getKey())); + zip.write(file.getValue()); + zip.closeEntry(); + } + } + return output.toByteArray(); + } +} diff --git a/web-ui/index.html b/web-ui/index.html new file mode 100644 index 0000000..92a01de --- /dev/null +++ b/web-ui/index.html @@ -0,0 +1,13 @@ + + + + + + + 智造申报 Agent + + +
+ + + diff --git a/web-ui/package-lock.json b/web-ui/package-lock.json new file mode 100644 index 0000000..33b55e7 --- /dev/null +++ b/web-ui/package-lock.json @@ -0,0 +1,3608 @@ +{ + "name": "smart-factory-approval-agent-client", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "smart-factory-approval-agent-client", + "version": "0.1.0", + "dependencies": { + "@ag-ui/client": "0.0.58", + "@element-plus/icons-vue": "^2.3.2", + "@lucide/vue": "^1.35.0", + "element-plus": "2.14.5", + "markstream-vue": "2.0.6", + "vue": "3.5.41", + "vue-router": "^4.6.3" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.1", + "@vue/test-utils": "^2.4.6", + "jsdom": "^26.1.0", + "typescript": "^5.9.3", + "vite": "^7.3.1", + "vitest": "^3.2.4", + "vue-tsc": "^3.2.2" + } + }, + "node_modules/@ag-ui/client": { + "version": "0.0.58", + "resolved": "https://registry.npmjs.org/@ag-ui/client/-/client-0.0.58.tgz", + "integrity": "sha512-9tAUJ6Ot0y2f5Va7xGFhUSO5OPAjilMsPdmKNmAUR774LKWcvNpriJ6mqH3p/ewUue1zfoUo4vpX+9Xo/zsuzA==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "0.0.58", + "@ag-ui/encoder": "0.0.58", + "@ag-ui/proto": "0.0.58", + "@types/uuid": "^10.0.0", + "compare-versions": "^6.1.1", + "fast-json-patch": "^3.1.1", + "rxjs": "7.8.1", + "untruncate-json": "^0.0.1", + "uuid": "^11.1.0", + "zod": "^3.22.4" + } + }, + "node_modules/@ag-ui/core": { + "version": "0.0.58", + "resolved": "https://registry.npmjs.org/@ag-ui/core/-/core-0.0.58.tgz", + "integrity": "sha512-XgGb7YmhV+yMBaEmlrpsd5S+nUxq0JgSegss2t4gIFR1j7w3w0ibtKfRgcQHWeMvwZxcT5S28VEEarqtgxYYHw==", + "license": "MIT", + "dependencies": { + "zod": "^3.22.4" + } + }, + "node_modules/@ag-ui/encoder": { + "version": "0.0.58", + "resolved": "https://registry.npmjs.org/@ag-ui/encoder/-/encoder-0.0.58.tgz", + "integrity": "sha512-eMfjJbfAGTQECgNX3QO0Mt0V5OrIViowSPmGLzdO92q2x506K2hRs2VBlfEuAzpDFp6Eq23Q/vjNHFzv37StZw==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "0.0.58", + "@ag-ui/proto": "0.0.58" + } + }, + "node_modules/@ag-ui/proto": { + "version": "0.0.58", + "resolved": "https://registry.npmjs.org/@ag-ui/proto/-/proto-0.0.58.tgz", + "integrity": "sha512-fErOnFPfpZlNSreeOEdUVuCzTQI463JoUo1DNx4grAvSZPOg4tVgqvG2s82qJE9pZoh48VSUqk6hyV82GT/wIA==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "0.0.58", + "@bufbuild/protobuf": "^2.2.5", + "@protobuf-ts/protoc": "^2.11.1" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", + "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bufbuild/protobuf": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.14.0.tgz", + "integrity": "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w==", + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, + "node_modules/@chenglou/pretext": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@chenglou/pretext/-/pretext-0.0.8.tgz", + "integrity": "sha512-yqm2GMxnPI7VHcHwe84P8ZF0JK/2d2DMKPqMN+s95jQhwDMYYXKVFVJUMEaVWckQStdsjdLav/0Vu+d9YbtGxA==", + "license": "MIT" + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.0.tgz", + "integrity": "sha512-kzyuwOAQnXJNLS9PSyrk0CWk35nWJW/zl/6KvnTBMFK65gm7U1/Z5BqjxeapjZCIhQcM/DsrEmcbRwDyXyXK4A==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@element-plus/icons-vue": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz", + "integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==", + "license": "MIT", + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@lucide/vue": { + "version": "1.35.0", + "resolved": "https://registry.npmjs.org/@lucide/vue/-/vue-1.35.0.tgz", + "integrity": "sha512-HTeJaMU7EUaeRqbZqaHyRg60UjiRdBAGwfWQRzORAspHh/H1rdnM/fdTzYX+SdL0OiUcAw+mM49G9D7zGgHzZg==", + "license": "ISC", + "peerDependencies": { + "vue": ">=3.0.1" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@one-ini/wasm": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@one-ini/wasm/-/wasm-0.1.1.tgz", + "integrity": "sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@popperjs/core": { + "name": "@sxzz/popperjs-es", + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz", + "integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@protobuf-ts/protoc": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/protoc/-/protoc-2.11.1.tgz", + "integrity": "sha512-mUZJaV0daGO6HUX90o/atzQ6A7bbN2RSuHtdwo8SSF2Qoe3zHwa4IHyCN1evftTeHfLmdz+45qo47sL+5P8nyg==", + "license": "Apache-2.0", + "bin": { + "protoc": "protoc.js" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.5.tgz", + "integrity": "sha512-jfkGfTwhQpsiSckPF8r9bU3pn3vyd72NlWaO+TgEO6WPSDnUhXzrNYCHBMOYj0ACaUgjm6eERLF+XV9a6RstoA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.5.tgz", + "integrity": "sha512-oGVqyQlxnrz9/ty89oHpU857VUHEl5/Xu4R2lS+aivCTrNnSsbiENzTnNaBsjxH0CNWGPhzHArOLFwo+oKXveA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.5.tgz", + "integrity": "sha512-bW7B8xMEq8n99Q3ieEcPRGuphurdZAaFzQc9Efyyw3FL6DZO6pMy9xhdN+kBoD7Sy05xNXSr4OyPPnpkYriS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.5.tgz", + "integrity": "sha512-YSwBS86QeHOGlrxJ1PSOIZSkzRL/JmKeunhc+lV6M1a6En8QuVCD/T/qIA0J4Gd2Y86RIOBYrLcOUtqGh9+/1w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.5.tgz", + "integrity": "sha512-2fST8lILgl7cKbme/1KDdPCmbXbG+gqoV3bHp19L0ypX/3akYMBVdOunPleRCwonoLnXOZ/0F+Mt/v8POFmfcQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.5.tgz", + "integrity": "sha512-cpIxQCP9J+EVad0a6LO1kY3ZGODlk80VlI+2I96B8xMcdHZ4pLVhfQ49JFpYqjPF91FFkQWftf57YlDcTiw9yQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.5.tgz", + "integrity": "sha512-r9fGh3eFs3e/udWh5ZjXQtxiYK/xoFxQaYR/cELxac/Udkl5Th+IsFm0CX3Kl9hmUH/we7EoMpjJgeQNnE0+IA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.5.tgz", + "integrity": "sha512-xdvFdp7OM6KLJviJT2g/YuRSUjnZgGHk4RNgwIbN7X6cPugOucV60DdHXWzsBVCUdrGb6qSXnJQrrAKMmQuj3Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.5.tgz", + "integrity": "sha512-rRqILAndyzHzP7T9NFQrq+4HFWNhqkqkKur7eiBpfLmz01PO0JKx5Vchu3YllE4YXI/Ftgq/szrDWg5GJ0mI8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.5.tgz", + "integrity": "sha512-Gf4X3qVMucayUvux6aXXPgXovocSFUC0rrffDuPI/S2nHhNMhjcZxsrAFYCOF350PRreW1XwzFj3CT/3bKsWCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.5.tgz", + "integrity": "sha512-+s5qA0TNM0qm8PK/a5gt/1Hpx+NV08uSuCncvhziIlQzT6AEV2fnUQo7eBtFTFO0nA9scauvoR2HusfXmQnO4w==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.5.tgz", + "integrity": "sha512-ybb6QvWwWJCbBWqERpc8K3pYVGIrXlG8MEQ8IIuJY6Y9KdHQxoFoNyfkAOtKn1VHu3KuLidXvwrvGR1mEjeWCw==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.5.tgz", + "integrity": "sha512-nZb1DtnOyhCmYvsC8A2CwOkopVg+IS1+fPUa7rMOAXtNw5+lLCLLPqd6XAiNrGtoQKsbvIBOwsHnBH/3wnb4HQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.5.tgz", + "integrity": "sha512-yMbj63Sp89ryrXLWyz+sy+fYD2HpOnMCLGbe4Oa1smclFSUukdtD/BgdiHaAetJNb74URD8U4hM+qG5KVzMEkg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.5.tgz", + "integrity": "sha512-mhoan3OJw2kYV/e1jtIdmvUZgyBFeA6zGWsOswmR0Tg19TQbowZuR+JMLID6spbbBN7Zee2ejrgmy3+FxGrIdA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.5.tgz", + "integrity": "sha512-5ZTLmjWbb1VZdjuyhe83K/8QO0/h11midQCBP+X5OYn32ra7eOBoM0ZqtaY4nkgNsYgmdVhMYPoyVPTjUpHf3w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.5.tgz", + "integrity": "sha512-m53kG+br6PGxOTmgBEM2DHSDs9RVjsyEbUwjJPJGTFm1grWOG8EKJggDCTb60unD4Tjby8fi7/m9XfkEWasVWg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.5.tgz", + "integrity": "sha512-6RHPJR1g/uvdYU8uXBnfq3nlqyZCP82Fr6NHgfGoaIeSh0YEqnX/x6uA9MmJJbnSH7swqX4F+CkGdUF+6doiQA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.5.tgz", + "integrity": "sha512-xs+OXQtEXgpXT0DmA5+U3qnRZHdCST/5HRQxS8wSPZTUZN/EMWeHuSIod32LQklTBZBV9DyfncKBQ8n5V3eFdw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.5.tgz", + "integrity": "sha512-e7hD+sl3s+mcLQDZ8pbudBVsdG6r5yN4w3LqG2TJ8sQHDpblWj5lrJs/3m01Cvlxbt4x13zu5thLjgypgtkYzw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.5.tgz", + "integrity": "sha512-GiyJaCf+WpMub/17aPcKk27QMl5W6f+KhdPTjlFOn5akH5Wa/DCM9Stdx5cDfmasyKB08MqpVQ1uJE2RkkpbXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.5.tgz", + "integrity": "sha512-+OQ8U2DdoEfXl8T4Fb18AjmEwbXMerKDKCL8yCPAYhKCEEKoul7rkbeGCBFCbAlaGaa7pmtRTpkAJM2LE/i5FA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.5.tgz", + "integrity": "sha512-KanvAZrPKbDBFwrgiU9yEVpQoox9QPV1WZOXX7HudJQY+eSlu82CtWxDU8WtuRRvtN5EGkLczkd6Y6DTcvm9wA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.5.tgz", + "integrity": "sha512-1aC3UEWTtRl3RK3VpDJ/Tqk1XI4SLTmXIthAq6wRWo8XiSXJNd+VprJM4/1P4+i6HIaFEFlVi9sTTziniD2tOQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.5.tgz", + "integrity": "sha512-/gDJaRs4gl0NPIwqCz+6PkpmhhjRAD2j6P4rSNHBzUkO3naEx2mIU0pRle1vUNRQ7mE/+8OOeXLTv/J56FKiQg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz", + "integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.21", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", + "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "6.0.8", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.8.tgz", + "integrity": "sha512-0ZjgOg7oO6farnNGup7yvoM/YXZV84OZxHAwtflItNa/6zzQyVb5LNxyea3FEKEX2XlagIKzrlH7wwxkKgtiew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz", + "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.28" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz", + "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz", + "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.41.tgz", + "integrity": "sha512-q0Xtv/F9w2YO/7htQhtiL+Ev2WCJbe5N2hc+XfgyKkEKqWpSxknmT8QOuGdEKNdjPq0c3F7rNpFkTo3Kfrm7pg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@vue/shared": "3.5.41", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.41.tgz", + "integrity": "sha512-oKacVfNglLvGjnS6BXOlGL7EyG2h8X03pqXCjzotRZUaXGjbrTJUnVAQjrCqUnS+lyu31nwQjZY/d817GmCnfw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.41", + "@vue/shared": "3.5.41" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.41.tgz", + "integrity": "sha512-XJhip7R2wy6vX3knCxdZN4KracFaZUef58s1KYewqluedHIJaPIVfXoYT7MF1F8nCvv6k8bWWxDC8opMkg1VTQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@vue/compiler-core": "3.5.41", + "@vue/compiler-dom": "3.5.41", + "@vue/compiler-ssr": "3.5.41", + "@vue/shared": "3.5.41", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.19", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.41.tgz", + "integrity": "sha512-U3v5OejKEGqOI0Wy0+Sz7hGuIFZHA4LSXzrNM3IMIeDyJEBBfTpX26n3SDgToRpP2bLc9FfI2j/kSgcJ8Emq5A==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.41", + "@vue/shared": "3.5.41" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.3.11.tgz", + "integrity": "sha512-QJmpliwAVpC/OxubIByPAhNzsQPRc8/gxlN2qnVzVfIMjMDz/9RnXRFoetjz5yEgXVXyp4LqhXq3V53PjmNzFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "@vue/compiler-dom": "^3.5.0", + "@vue/shared": "^3.5.0", + "alien-signals": "^3.2.1", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1", + "picomatch": "^4.0.4" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.41.tgz", + "integrity": "sha512-rznsqKM0np0x18EjzF8x88MpEhdNsffbvFbckLL5+oUKz1BxAImEmO7J1ArRYSyo6aQaVoBDp7jEkT91OOxydA==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.41" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.41.tgz", + "integrity": "sha512-Vcry58hiAKwGen9Z1jUZE0feFsNArPCMOImYI8el48A9Idf6DuQYD0U05zZIF2Iad1hGhPSvcbBbAOhNr55fhg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.41", + "@vue/shared": "3.5.41" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.41.tgz", + "integrity": "sha512-3vVBahVBS9+U6cmXBLyb8nE6/yYo4J/CGI9eVFs3KiMc0YHuudwKyShTD65jtJy/L9PUUxNAFu4cj4LiJ0UFbw==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.41", + "@vue/runtime-core": "3.5.41", + "@vue/shared": "3.5.41", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.41.tgz", + "integrity": "sha512-n6hx/pNFfbD6SuyeuMVkvqox8bwf/ET9JlA/kAz/imw8sw++wkqKe2mHX5KutjPpbKE4Z56yTHszoOjGMI9igQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.41", + "@vue/runtime-dom": "3.5.41", + "@vue/shared": "3.5.41" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.41.tgz", + "integrity": "sha512-IOnwSCma8j+9xJT6b8H0dEYidC80NsYmNMlZxRsukYcSoGaDBohog5hDxzeUXdFeGWFA++vWvxqOmrr96VlqMA==", + "license": "MIT" + }, + "node_modules/@vue/test-utils": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@vue/test-utils/-/test-utils-2.4.11.tgz", + "integrity": "sha512-GDqaqZsA6m2E5vNzej0aYiIb6BX8xV9pNSbbbXKOfEYwg7ZNblVX8suyqmUBThq8VIrgAJNxn+z72hVtUeiWHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-beautify": "^1.14.9", + "vue-component-type-helpers": "^3.0.0" + }, + "peerDependencies": { + "@vue/compiler-dom": "3.x", + "@vue/server-renderer": "3.x", + "vue": "3.x" + }, + "peerDependenciesMeta": { + "@vue/server-renderer": { + "optional": true + } + } + }, + "node_modules/@vueuse/core": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz", + "integrity": "sha512-X4WHz1HlCzCBoYXesUkifzzWBAcZgXG8Fi5iNPQg/epdzOB3gu8Fawj3hvuwYR1nGcXGnvxwYYcUC/71++svtQ==", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "14.4.0", + "@vueuse/shared": "14.4.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/@vueuse/metadata": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz", + "integrity": "sha512-swx/255R6JyHZFJhx845iz5CRWDZdCfvkZOpACWc5+c5WHcG24mv8gUT1WIdFQaHt6dq79rvILd9QnCWiyVm9g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz", + "integrity": "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/abbrev": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz", + "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/alien-signals": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.2.1.tgz", + "integrity": "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-regex": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", + "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/async-validator": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz", + "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", + "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/compare-versions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "license": "MIT" + }, + "node_modules/config-chain": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", + "integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/dayjs": { + "version": "1.11.23", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/editorconfig": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.7.tgz", + "integrity": "sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@one-ini/wasm": "0.1.1", + "commander": "^10.0.0", + "minimatch": "^9.0.1", + "semver": "^7.5.3" + }, + "bin": { + "editorconfig": "bin/editorconfig" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/element-plus": { + "version": "2.14.5", + "resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz", + "integrity": "sha512-bghYy/S+qg87enHPXELirhEdDqsVAUGcGpbGIeG8dz0kwpIkGz7gYsifulBshXX74iRtHib85XWQj0uSH2A1Yg==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^4.2.0", + "@element-plus/icons-vue": "^2.3.2", + "@floating-ui/dom": "^1.8.0", + "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.8", + "@types/lodash": "^4.17.24", + "@types/lodash-es": "^4.17.12", + "@vueuse/core": "14.4.0", + "async-validator": "^4.2.5", + "dayjs": "^1.11.20", + "lodash": "^4.18.1", + "lodash-es": "^4.18.1", + "lodash-unified": "^1.0.3", + "memoize-one": "^6.0.0", + "normalize-wheel-es": "^1.2.0", + "vue-component-type-helpers": "^3.3.9" + }, + "peerDependencies": { + "vue": "^3.3.7" + } + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-json-patch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.1.tgz", + "integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/js-beautify": { + "version": "1.15.4", + "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.4.tgz", + "integrity": "sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "config-chain": "^1.1.13", + "editorconfig": "^1.0.4", + "glob": "^10.4.2", + "js-cookie": "^3.0.5", + "nopt": "^7.2.1" + }, + "bin": { + "css-beautify": "js/bin/css-beautify.js", + "html-beautify": "js/bin/html-beautify.js", + "js-beautify": "js/bin/js-beautify.js" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/js-cookie": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz", + "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/lodash-unified": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/lodash-unified/-/lodash-unified-1.0.3.tgz", + "integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==", + "license": "MIT", + "peerDependencies": { + "@types/lodash-es": "*", + "lodash": "*", + "lodash-es": "*" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/markdown-it-container": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-container/-/markdown-it-container-4.0.0.tgz", + "integrity": "sha512-HaNccxUH0l7BNGYbFbjmGpf5aLHAMTinqRZQAEQbMr2cdD3z91Q6kIo1oUn1CQndkT03jat6ckrdRYuwwqLlQw==", + "license": "MIT" + }, + "node_modules/markdown-it-footnote": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-footnote/-/markdown-it-footnote-4.0.0.tgz", + "integrity": "sha512-WYJ7urf+khJYl3DqofQpYfEYkZKbmXmwxQV8c8mO/hGIhgZ1wOe7R4HLFNwqx7TjILbnC98fuyeSsin19JdFcQ==", + "license": "MIT" + }, + "node_modules/markdown-it-ins": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-ins/-/markdown-it-ins-4.0.0.tgz", + "integrity": "sha512-sWbjK2DprrkINE4oYDhHdCijGT+MIDhEupjSHLXe5UXeVr5qmVxs/nTUVtgi0Oh/qtF+QKV0tNWDhQBEPxiMew==", + "license": "MIT" + }, + "node_modules/markdown-it-mark": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-mark/-/markdown-it-mark-4.0.0.tgz", + "integrity": "sha512-YLhzaOsU9THO/cal0lUjfMjrqSMPjjyjChYM7oyj4DnyaXEzA8gnW6cVJeyCrCVeyesrY2PlEdUYJSPFYL4Nkg==", + "license": "MIT" + }, + "node_modules/markdown-it-sup": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-sup/-/markdown-it-sup-2.0.0.tgz", + "integrity": "sha512-5VgmdKlkBd8sgXuoDoxMpiU+BiEt3I49GItBzzw7Mxq9CxvnhE/k09HFli09zgfFDRixDQDfDxi0mgBCXtaTvA==", + "license": "MIT" + }, + "node_modules/markdown-it-task-checkbox": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/markdown-it-task-checkbox/-/markdown-it-task-checkbox-1.0.6.tgz", + "integrity": "sha512-7pxkHuvqTOu3iwVGmDPeYjQg+AIS9VQxzyLP9JCg9lBjgPAJXGEkChK6A2iFuj3tS0GV3HG2u5AMNhcQqwxpJw==", + "license": "ISC" + }, + "node_modules/markdown-it-ts": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/markdown-it-ts/-/markdown-it-ts-1.1.0.tgz", + "integrity": "sha512-ycYoj3jeP0zHW9u4vxtSuuq9JaitIRxxYbRtns9D4fDR5mzSpFnb855KclFBGiKFJxVi+8EkMB938oZpdDVc0A==", + "license": "MIT", + "dependencies": { + "entities": "^8.0.0", + "linkify-it": "^6.1.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1" + }, + "engines": { + "node": ">=20.19" + } + }, + "node_modules/markdown-it-ts/node_modules/entities": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", + "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/markstream-core": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/markstream-core/-/markstream-core-2.0.6.tgz", + "integrity": "sha512-kSGNAoTArTu9LxwyfZI+fuxanjhxwPtlW+yJM+5IJhW2jtsH9p7mSpApHC6YtJLnzeXCGS2XlqIoivzIdzy6iA==", + "license": "MIT" + }, + "node_modules/markstream-vue": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/markstream-vue/-/markstream-vue-2.0.6.tgz", + "integrity": "sha512-87skNadimBbQFZbb6kNgIrCpXr5x63YW4MYkRbWHh/g/1+BHJ2t3iIzEsSIIES1yn29STf4ZLw1ruepZqXZeXg==", + "license": "MIT", + "dependencies": { + "@chenglou/pretext": "^0.0.8", + "@floating-ui/dom": "^1.8.0", + "markstream-core": "2.0.6", + "stream-markdown-parser": "1.2.12" + }, + "peerDependencies": { + "@antv/infographic": "^0.2.3", + "@terrastruct/d2": ">=0.1.33", + "katex": ">=0.16.22", + "mermaid": ">=11", + "stream-diffs": ">=0.0.2", + "vue": ">=3.0.0", + "vue-i18n": ">=9" + }, + "peerDependenciesMeta": { + "@antv/infographic": { + "optional": true + }, + "@terrastruct/d2": { + "optional": true + }, + "katex": { + "optional": true + }, + "mermaid": { + "optional": true + }, + "stream-diffs": { + "optional": true + }, + "vue-i18n": { + "optional": true + } + } + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz", + "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nopt": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz", + "integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/normalize-wheel-es": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz", + "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", + "license": "BSD-3-Clause" + }, + "node_modules/nwsapi": { + "version": "2.2.24", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.24.tgz", + "integrity": "sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==", + "dev": true, + "license": "MIT" + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.26", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", + "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.17", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proto-list": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz", + "integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==", + "dev": true, + "license": "ISC" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.62.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.5.tgz", + "integrity": "sha512-/tqMfgP7GPA3PHhCmuiS4vIjrSVhHLgY++i+dhbG462euyAj7FpM4D9uq1X3BgjlqRdpcOrYhcQtfiQLNc8tqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.62.5", + "@rollup/rollup-android-arm64": "4.62.5", + "@rollup/rollup-darwin-arm64": "4.62.5", + "@rollup/rollup-darwin-x64": "4.62.5", + "@rollup/rollup-freebsd-arm64": "4.62.5", + "@rollup/rollup-freebsd-x64": "4.62.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.5", + "@rollup/rollup-linux-arm-musleabihf": "4.62.5", + "@rollup/rollup-linux-arm64-gnu": "4.62.5", + "@rollup/rollup-linux-arm64-musl": "4.62.5", + "@rollup/rollup-linux-loong64-gnu": "4.62.5", + "@rollup/rollup-linux-loong64-musl": "4.62.5", + "@rollup/rollup-linux-ppc64-gnu": "4.62.5", + "@rollup/rollup-linux-ppc64-musl": "4.62.5", + "@rollup/rollup-linux-riscv64-gnu": "4.62.5", + "@rollup/rollup-linux-riscv64-musl": "4.62.5", + "@rollup/rollup-linux-s390x-gnu": "4.62.5", + "@rollup/rollup-linux-x64-gnu": "4.62.5", + "@rollup/rollup-linux-x64-musl": "4.62.5", + "@rollup/rollup-openbsd-x64": "4.62.5", + "@rollup/rollup-openharmony-arm64": "4.62.5", + "@rollup/rollup-win32-arm64-msvc": "4.62.5", + "@rollup/rollup-win32-ia32-msvc": "4.62.5", + "@rollup/rollup-win32-x64-gnu": "4.62.5", + "@rollup/rollup-win32-x64-msvc": "4.62.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/stream-markdown-parser": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/stream-markdown-parser/-/stream-markdown-parser-1.2.12.tgz", + "integrity": "sha512-gT6GWlOfNTVGBEM66Me1DZ1cZZ/Mm4tcpJ4br8Zvz2CQhiWueEv+xFBBHCwls/XG4E63DygTd890rDdV+D6JxA==", + "license": "MIT", + "dependencies": { + "markdown-it-container": "^4.0.0", + "markdown-it-footnote": "^4.0.0", + "markdown-it-ins": "^4.0.0", + "markdown-it-mark": "^4.0.0", + "markdown-it-sup": "^2.0.0", + "markdown-it-task-checkbox": "^1.0.6", + "markdown-it-ts": "^1.1.0" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "license": "MIT" + }, + "node_modules/untruncate-json": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/untruncate-json/-/untruncate-json-0.0.1.tgz", + "integrity": "sha512-4W9enDK4X1y1s2S/Rz7ysw6kDuMS3VmRjMFg7GZrNO+98OSe+x5Lh7PKYoVjy3lW/1wmhs6HW0lusnQRHgMarA==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/vite": { + "version": "7.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", + "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.41", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.41.tgz", + "integrity": "sha512-2laE0p+aK+/AOPG/XL/WepOs/GlK755LJ1XECi9kDUrz1FKNw8rb2Xzlw9JS1rqEV55nb0ttsKxVlTCcd+R5cg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.41", + "@vue/compiler-sfc": "3.5.41", + "@vue/runtime-dom": "3.5.41", + "@vue/server-renderer": "3.5.41", + "@vue/shared": "3.5.41" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-component-type-helpers": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz", + "integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==", + "license": "MIT" + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.3.11.tgz", + "integrity": "sha512-gOb0B9rtU2+f1dszwPqSH5kAieIF9ReeLhD3kSRNHv5WZZUQz/JdVXW0RTdqhNTMlQkqKzrTTviqKr/4FYZraQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.28", + "@vue/language-core": "3.3.11" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/web-ui/package.json b/web-ui/package.json new file mode 100644 index 0000000..b2ce66d --- /dev/null +++ b/web-ui/package.json @@ -0,0 +1,29 @@ +{ + "name": "smart-factory-approval-agent-client", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite --host 127.0.0.1", + "build": "vue-tsc -b && vite build", + "test": "vitest run" + }, + "dependencies": { + "@ag-ui/client": "0.0.58", + "@element-plus/icons-vue": "^2.3.2", + "@lucide/vue": "^1.35.0", + "element-plus": "2.14.5", + "markstream-vue": "2.0.6", + "vue": "3.5.41", + "vue-router": "^4.6.3" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.1", + "@vue/test-utils": "^2.4.6", + "jsdom": "^26.1.0", + "typescript": "^5.9.3", + "vite": "^7.3.1", + "vitest": "^3.2.4", + "vue-tsc": "^3.2.2" + } +} diff --git a/web-ui/src/App.vue b/web-ui/src/App.vue new file mode 100644 index 0000000..d708285 --- /dev/null +++ b/web-ui/src/App.vue @@ -0,0 +1,106 @@ + + + diff --git a/web-ui/src/api.ts b/web-ui/src/api.ts new file mode 100644 index 0000000..0a33cc7 --- /dev/null +++ b/web-ui/src/api.ts @@ -0,0 +1,142 @@ +export interface Project { + id: string + companyName: string + projectName: string + threadId: string + applicationLevel: 'ADVANCED' | 'EXCELLENT' + status: 'MATERIAL_CHECK' | 'PLANNING' | 'WRITING' | 'DELIVERED' | 'FAILED' | 'ARCHIVED' + createdAt: string + updatedAt: string +} + +export interface ProjectFile { + id: string + name: string + relativePath: string + extension: string + sizeBytes: number + status: string + createdAt: string +} + +export interface AgentEvent { + id: number + projectId: string + runId: string | null + type: string + payload: Record + createdAt: string +} + +export interface PlanView { + id: string + status: string + version: number + plan: Record +} + +export interface Artifact { + id: string + name: string + kind: string + sizeBytes: number + metadataJson: string + publishedAt: string +} + +let csrf: { token: string; headerName: string } | null = null + +async function ensureCsrf() { + if (!csrf) csrf = await raw('/api/auth/csrf') + return csrf! +} + +async function raw(path: string, options: RequestInit = {}) { + const response = await fetch(path, { credentials: 'include', ...options }) + if (response.status === 401 && path !== '/api/auth/login') { + location.assign('/login') + throw new Error('登录状态已失效') + } + if (!response.ok) { + const body = await response.json().catch(() => ({ message: `请求失败(${response.status})` })) + throw new Error(body.message || `请求失败(${response.status})`) + } + if (response.status === 204) return null + return response.json() +} + +export async function api(path: string, options: RequestInit = {}): Promise { + const method = (options.method || 'GET').toUpperCase() + const headers = new Headers(options.headers) + if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) { + const token = await ensureCsrf() + headers.set(token.headerName, token.token) + } + if (options.body && !(options.body instanceof FormData)) headers.set('Content-Type', 'application/json') + return raw(path, { ...options, headers }) +} + +export async function login(username: string, password: string) { + csrf = null + return raw('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }) + }) +} + +export function streamEvents( + projectId: string, + after: number, + onEvents: (events: AgentEvent[]) => void, + onError: (error: Error) => void +) { + const controller = new AbortController() + let cursor = after + let stopped = false + + const connect = async () => { + while (!stopped) { + try { + const response = await fetch(`/api/projects/${projectId}/events/stream?after=${cursor}`, { + credentials: 'include', + signal: controller.signal, + headers: { Accept: 'application/x-ndjson' } + }) + if (response.status === 401) { + location.assign('/login') + return + } + if (!response.ok || !response.body) throw new Error(`事件流连接失败(${response.status})`) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let buffer = '' + while (!stopped) { + const { done, value } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + const lines = buffer.split('\n') + buffer = lines.pop() || '' + const batch = lines + .filter(Boolean) + .map(line => JSON.parse(line) as AgentEvent) + .filter(event => event.type !== 'HEARTBEAT') + if (batch.length) { + cursor = batch.at(-1)!.id + onEvents(batch) + } + } + if (!stopped) await new Promise(resolve => setTimeout(resolve, 1200)) + } catch (error) { + if (controller.signal.aborted) return + onError(error instanceof Error ? error : new Error('事件流异常')) + await new Promise(resolve => setTimeout(resolve, 1200)) + } + } + } + void connect() + return () => { + stopped = true + controller.abort() + } +} diff --git a/web-ui/src/components/AgentTimeline.test.ts b/web-ui/src/components/AgentTimeline.test.ts new file mode 100644 index 0000000..909734c --- /dev/null +++ b/web-ui/src/components/AgentTimeline.test.ts @@ -0,0 +1,131 @@ +// @vitest-environment jsdom +import { flushPromises, mount, shallowMount } from '@vue/test-utils' +import { ElImageViewer } from 'element-plus' +import { describe, expect, it, vi } from 'vitest' + +import AgentTimeline from './AgentTimeline.vue' + +describe('AgentTimeline', () => { + it('运行中但没有真实增量时不渲染占位消息', () => { + const wrapper = shallowMount(AgentTimeline, { props: { events: [], running: true, projectId: 'p' } }) + + expect(wrapper.findAll('article')).toHaveLength(0) + expect(wrapper.text()).not.toContain('Agent 正在继续执行') + expect(wrapper.text()).not.toContain('思考中') + }) + + it('终态不渲染暂停输出占位提示', () => { + const wrapper = shallowMount(AgentTimeline, { props: { events: [], running: false, projectId: 'p' } }) + + expect(wrapper.text()).not.toContain('Agent 已暂停输出') + expect(wrapper.text()).not.toContain('Agent 正在执行') + }) + + it('展示真实的模型重连和用户停止事件', () => { + const wrapper = shallowMount(AgentTimeline, { props: { running: false, projectId: 'p', events: [ + { id: 1, projectId: 'p', runId: 'r', type: 'MODEL_RETRY', payload: { attempt: 2, maxAttempts: 5 }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'tool-1', toolCallName: 'execute' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 3, projectId: 'p', runId: 'r', type: 'RUN_FINISHED', payload: { outcome: 'CANCELLED' }, createdAt: '2026-08-24T10:00:01Z' }, + { id: 4, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'late-tool', toolCallName: 'write_file' }, createdAt: '2026-08-24T10:00:02Z' } + ] } }) + + expect(wrapper.text()).toContain('模型连接中断,正在重连(2/5)') + expect(wrapper.text()).toContain('已停止') + expect(wrapper.text()).toContain('Agent 已停止,当前上下文已保留') + expect(wrapper.text()).not.toContain('运行中') + }) + + it('完成后展示已调用的工具和 Skill 名称', () => { + const events = [ + { id: 1, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'a', toolCallName: 'read_file' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r', type: 'TOOL_CALL_ARGS', payload: { toolCallId: 'a', delta: '{"path":"inputs/report.md"}' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 3, projectId: 'p', runId: 'r', type: 'TOOL_CALL_END', payload: { toolCallId: 'a' }, createdAt: '2026-08-24T10:00:01Z' }, + { id: 4, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'b', toolCallName: 'load_skill_through_path' }, createdAt: '2026-08-24T10:00:02Z' }, + { id: 5, projectId: 'p', runId: 'r', type: 'TOOL_CALL_ARGS', payload: { toolCallId: 'b', delta: '{"skillId":"pdf_imported"}' }, createdAt: '2026-08-24T10:00:02Z' }, + { id: 6, projectId: 'p', runId: 'r', type: 'TOOL_CALL_END', payload: { toolCallId: 'b' }, createdAt: '2026-08-24T10:00:03Z' }, + { id: 7, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'c', toolCallName: 'write_file' }, createdAt: '2026-08-24T10:00:04Z' }, + { id: 8, projectId: 'p', runId: 'r', type: 'TOOL_CALL_ARGS', payload: { toolCallId: 'c', delta: '{"path":"work/material-check.json"}' }, createdAt: '2026-08-24T10:00:04Z' } + ] + const wrapper = shallowMount(AgentTimeline, { props: { events, running: false, projectId: 'p' } }) + + expect(wrapper.text()).toContain('已读取 report.md 文件') + expect(wrapper.text()).toContain('正在编辑 material-check.json 文件') + expect(wrapper.text()).toContain('已调用 pdf Skill') + }) + + it('每个 Run 只展示一次身份并安全渲染 Markdown 正文', async () => { + const events = [ + { id: 1, projectId: 'p', runId: 'r1', type: 'TEXT_MESSAGE_CONTENT', payload: { messageId: 'm1', delta: '## 分析\n\n**关键结论**' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r1', type: 'TEXT_MESSAGE_CONTENT', payload: { messageId: 'm2', delta: '- 第一项\n- 第二项' }, createdAt: '2026-08-24T10:00:01Z' }, + { id: 3, projectId: 'p', runId: 'r2', type: 'TEXT_MESSAGE_CONTENT', payload: { messageId: 'm3', delta: '' }, createdAt: '2026-08-24T10:00:02Z' } + ] + const wrapper = mount(AgentTimeline, { props: { events, running: false, projectId: 'p' } }) + await flushPromises() + await vi.waitFor(() => expect(wrapper.find('.agent-markdown h2').exists()).toBe(true)) + + expect(wrapper.findAll('.agent-avatar')).toHaveLength(2) + expect(wrapper.findAll('.flow-meta')).toHaveLength(2) + expect(wrapper.find('.agent-markdown h2').text()).toBe('分析') + expect(wrapper.find('.agent-markdown strong').text()).toBe('关键结论') + expect(wrapper.findAll('.agent-markdown li')).toHaveLength(2) + expect(wrapper.find('script').exists()).toBe(false) + }) + + it('完整展示正文并在浮层画廊中查看全部视觉结果', async () => { + const body = '正文'.repeat(500) + const result = 'document_view_result={"images":[{"index":1,"path":"work/tmp/document-view/a/render-1.png","sourcePath":"inputs/a.pdf","label":"第 1 页"},{"index":2,"path":"work/tmp/document-view/a/render-2.png","sourcePath":"inputs/a.pdf","label":"第 2 页"}],"errors":[]}' + const events = [ + { id: 1, projectId: 'p', runId: 'r', type: 'TEXT_MESSAGE_CONTENT', payload: { messageId: 'm', delta: body }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r', type: 'TOOL_CALL_START', payload: { toolCallId: 'v', toolCallName: 'document_view' }, createdAt: '2026-08-24T10:00:01Z' }, + { id: 3, projectId: 'p', runId: 'r', type: 'TOOL_CALL_RESULT', payload: { toolCallId: 'v', content: result }, createdAt: '2026-08-24T10:00:02Z' } + ] + const wrapper = mount(AgentTimeline, { props: { events, running: false, projectId: 'p' } }) + await flushPromises() + await vi.waitFor(() => expect(wrapper.find('.agent-markdown').exists()).toBe(true)) + + expect(wrapper.text()).toContain(body) + expect(wrapper.text()).not.toContain('展开完整输出') + expect(wrapper.text()).toContain('已查看图片 · 2 张') + expect(wrapper.findAll('.view-image-item')).toHaveLength(2) + expect(wrapper.find('a[target="_blank"]').exists()).toBe(false) + + await wrapper.findAll('.view-image-item')[1].trigger('click') + expect(wrapper.findComponent(ElImageViewer).props('initialIndex')).toBe(1) + expect(wrapper.findComponent(ElImageViewer).props('urlList')).toHaveLength(2) + }) + + it('模型正文结束后延迟展示真实的结果整理状态', async () => { + vi.useFakeTimers() + const events = [ + { id: 1, projectId: 'p', runId: 'r', type: 'TEXT_MESSAGE_CONTENT', payload: { messageId: 'm', delta: '规划完成' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r', type: 'TEXT_MESSAGE_END', payload: { messageId: 'm' }, createdAt: '2026-08-24T10:00:01Z' } + ] + const wrapper = shallowMount(AgentTimeline, { props: { events, running: true, projectId: 'p' } }) + + expect(wrapper.text()).not.toContain('正在整理结果') + vi.advanceTimersByTime(500) + await wrapper.vm.$nextTick() + expect(wrapper.text()).toContain('正在整理结果') + + await wrapper.setProps({ events: [...events, { + id: 3, projectId: 'p', runId: 'r', type: 'ASK_REQUESTED', payload: { kind: 'planning' }, createdAt: '2026-08-24T10:00:02Z' + }] }) + expect(wrapper.text()).not.toContain('正在整理结果') + wrapper.unmount() + vi.useRealTimers() + }) + + it('材料确认后在时间线保留只读摘要', () => { + const events = [ + { id: 1, projectId: 'p', runId: 'r', type: 'ASK_REQUESTED', payload: { kind: 'material_check' }, createdAt: '2026-08-24T10:00:00Z' }, + { id: 2, projectId: 'p', runId: 'r', type: 'ASK_RESPONDED', payload: { decisions: [ + { id: 'a', action: 'ASSUMPTION' }, + { id: 'b', action: 'PENDING_COMMENT' }, + { id: 'c', action: 'UPLOADED' } + ] }, createdAt: '2026-08-24T10:00:01Z' } + ] + const wrapper = shallowMount(AgentTimeline, { props: { events, running: false, projectId: 'p' } }) + + expect(wrapper.text()).toContain('已确认材料检验 · 1 项按规划假设继续 · 1 项待确认 · 1 项已补充') + }) +}) diff --git a/web-ui/src/components/AgentTimeline.vue b/web-ui/src/components/AgentTimeline.vue new file mode 100644 index 0000000..d9c39a8 --- /dev/null +++ b/web-ui/src/components/AgentTimeline.vue @@ -0,0 +1,371 @@ + + + diff --git a/web-ui/src/components/MaterialAskCard.vue b/web-ui/src/components/MaterialAskCard.vue new file mode 100644 index 0000000..69eb442 --- /dev/null +++ b/web-ui/src/components/MaterialAskCard.vue @@ -0,0 +1,112 @@ + + + diff --git a/web-ui/src/components/PlanCard.vue b/web-ui/src/components/PlanCard.vue new file mode 100644 index 0000000..51f8dce --- /dev/null +++ b/web-ui/src/components/PlanCard.vue @@ -0,0 +1,91 @@ + + + diff --git a/web-ui/src/eventCache.ts b/web-ui/src/eventCache.ts new file mode 100644 index 0000000..ba602fa --- /dev/null +++ b/web-ui/src/eventCache.ts @@ -0,0 +1,57 @@ +import type { AgentEvent } from './api' + +const DB_NAME = 'smart-factory-agent' +const STORE_NAME = 'events' + +function openDatabase() { + return new Promise((resolve, reject) => { + const request = indexedDB.open(DB_NAME, 1) + request.onupgradeneeded = () => { + const store = request.result.createObjectStore(STORE_NAME, { keyPath: ['projectId', 'id'] }) + store.createIndex('projectId', 'projectId') + } + request.onsuccess = () => resolve(request.result) + request.onerror = () => reject(request.error) + }) +} + +export async function readCachedEvents(projectId: string): Promise { + const database = await openDatabase() + return new Promise((resolve, reject) => { + const transaction = database.transaction(STORE_NAME, 'readonly') + const request = transaction.objectStore(STORE_NAME).index('projectId').getAll(projectId) + request.onsuccess = () => resolve((request.result as AgentEvent[]).sort((a, b) => a.id - b.id)) + request.onerror = () => reject(request.error) + transaction.oncomplete = () => database.close() + }) +} + +export async function cacheEvents(events: AgentEvent[]) { + if (!events.length) return + const database = await openDatabase() + await new Promise((resolve, reject) => { + const transaction = database.transaction(STORE_NAME, 'readwrite') + const store = transaction.objectStore(STORE_NAME) + for (const event of events) store.put(event) + transaction.oncomplete = () => resolve() + transaction.onerror = () => reject(transaction.error) + }) + database.close() +} + +export async function deleteCachedEvents(projectId: string) { + const database = await openDatabase() + await new Promise((resolve, reject) => { + const transaction = database.transaction(STORE_NAME, 'readwrite') + const request = transaction.objectStore(STORE_NAME).index('projectId').openCursor(IDBKeyRange.only(projectId)) + request.onsuccess = () => { + const cursor = request.result + if (!cursor) return + cursor.delete() + cursor.continue() + } + transaction.oncomplete = () => resolve() + transaction.onerror = () => reject(transaction.error) + }) + database.close() +} diff --git a/web-ui/src/eventUtils.test.ts b/web-ui/src/eventUtils.test.ts new file mode 100644 index 0000000..05e75e3 --- /dev/null +++ b/web-ui/src/eventUtils.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import type { AgentEvent } from './api' +import { appendUniqueEvents } from './eventUtils' + +const event = (id: number): AgentEvent => ({ + id, + projectId: 'project', + runId: 'run', + type: 'TEXT_MESSAGE_CONTENT', + payload: { delta: String(id) }, + createdAt: '2026-08-24T00:00:00Z' +}) + +describe('appendUniqueEvents', () => { + it('保留顺序并忽略重放事件', () => { + expect(appendUniqueEvents([event(1), event(2)], [event(2), event(3)]).map(item => item.id)) + .toEqual([1, 2, 3]) + }) +}) diff --git a/web-ui/src/eventUtils.ts b/web-ui/src/eventUtils.ts new file mode 100644 index 0000000..2dcb2c9 --- /dev/null +++ b/web-ui/src/eventUtils.ts @@ -0,0 +1,10 @@ +import type { AgentEvent } from './api' + +/** 合并重连批次并按事件主键去重。 */ +export function appendUniqueEvents(current: AgentEvent[], incoming: AgentEvent[]) { + if (!incoming.length) return current + const lastId = current.at(-1)?.id + if (lastId == null || incoming[0].id > lastId) return current.concat(incoming) + const ids = new Set(current.map(event => event.id)) + return current.concat(incoming.filter(event => !ids.has(event.id))) +} diff --git a/web-ui/src/main.ts b/web-ui/src/main.ts new file mode 100644 index 0000000..9df36fe --- /dev/null +++ b/web-ui/src/main.ts @@ -0,0 +1,32 @@ +import { createApp } from 'vue' +import { + ElButton, + ElDialog, + ElForm, + ElFormItem, + ElIcon, + ElInput, + ElInputNumber, + ElOption, + ElRadioButton, + ElRadioGroup, + ElSelect, + ElSwitch, + ElTabPane, + ElTabs, + ElUpload +} from 'element-plus' +import 'element-plus/dist/index.css' +import 'markstream-vue/index.css' +import './styles.css' +import App from './App.vue' +import { router } from './router' + +const app = createApp(App) +for (const component of [ + ElButton, ElDialog, ElForm, ElFormItem, ElIcon, ElInput, + ElInputNumber, ElOption, ElRadioButton, ElRadioGroup, ElSelect, + ElSwitch, ElTabPane, ElTabs, ElUpload +]) app.component(component.name!, component) +app.use(router) +void router.isReady().then(() => app.mount('#app')) diff --git a/web-ui/src/pages/LoginPage.vue b/web-ui/src/pages/LoginPage.vue new file mode 100644 index 0000000..3434265 --- /dev/null +++ b/web-ui/src/pages/LoginPage.vue @@ -0,0 +1,45 @@ + + + diff --git a/web-ui/src/pages/ModelsPage.vue b/web-ui/src/pages/ModelsPage.vue new file mode 100644 index 0000000..6dcc41b --- /dev/null +++ b/web-ui/src/pages/ModelsPage.vue @@ -0,0 +1,124 @@ + + + diff --git a/web-ui/src/pages/ProjectPage.vue b/web-ui/src/pages/ProjectPage.vue new file mode 100644 index 0000000..017ced8 --- /dev/null +++ b/web-ui/src/pages/ProjectPage.vue @@ -0,0 +1,426 @@ + + + diff --git a/web-ui/src/pages/SkillsPage.vue b/web-ui/src/pages/SkillsPage.vue new file mode 100644 index 0000000..55bb34e --- /dev/null +++ b/web-ui/src/pages/SkillsPage.vue @@ -0,0 +1,89 @@ + + + diff --git a/web-ui/src/router.ts b/web-ui/src/router.ts new file mode 100644 index 0000000..05a1bcd --- /dev/null +++ b/web-ui/src/router.ts @@ -0,0 +1,13 @@ +import { createRouter, createWebHistory } from 'vue-router' + +export const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/login', component: () => import('./pages/LoginPage.vue'), meta: { public: true } }, + { path: '/', redirect: '/projects' }, + { path: '/projects', component: () => import('./pages/ProjectPage.vue') }, + { path: '/projects/:id', component: () => import('./pages/ProjectPage.vue') }, + { path: '/models', component: () => import('./pages/ModelsPage.vue') }, + { path: '/skills', component: () => import('./pages/SkillsPage.vue') } + ] +}) diff --git a/web-ui/src/styles.css b/web-ui/src/styles.css new file mode 100644 index 0000000..753dfa1 --- /dev/null +++ b/web-ui/src/styles.css @@ -0,0 +1,247 @@ +:root { + font-family: Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; + color: #111827; + background: #fff; + font-synthesis: none; + --blue: #0f5df5; + --blue-soft: #f2f7ff; + --muted: #667085; + --line: #e8edf5; + --green: #087d41; +} + +* { box-sizing: border-box; } +body { margin: 0; min-width: 0; min-height: 100vh; } +button, input, textarea { font: inherit; } +a { color: inherit; text-decoration: none; } + +.app-shell { min-height: 100vh; display: flex; background: #fff; } +.rail { width: 84px; flex: 0 0 84px; height: 100vh; position: sticky; top: 0; border-right: 1px solid var(--line); display: flex; flex-direction: column; align-items: center; padding: 20px 10px; gap: 18px; } +.brand { width: 46px; height: 46px; border-radius: 9px; background: var(--blue); color: #fff; display: grid; place-items: center; font-weight: 700; } +.brand svg { width: 24px; } +.rail a { width: 64px; height: 66px; border-radius: 9px; color: #405170; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; font-size: 15px; } +.rail a svg { width: 24px; height: 24px; } +.rail a.active { background: var(--blue); color: #fff; } +.rail .brand + a { margin-top: 6px; } + +.project-list { width: 276px; flex: 0 0 276px; height: 100vh; position: sticky; top: 0; overflow-y: auto; border-right: 1px solid var(--line); padding: 24px 16px; background: #fff; } +.aside-title { display: flex; align-items: center; justify-content: space-between; padding: 0 12px; } +.aside-title h2 { font-size: 20px; margin: 0; } +.icon-button { width: 32px; height: 32px; border: 1px solid #9aa8bd; border-radius: 50%; background: #fff; color: #395277; font-size: 23px; line-height: 27px; cursor: pointer; } +.aside-label { margin: 32px 12px 12px; color: #596883; font-size: 14px; } +.project-item { display: flex; flex-direction: column; gap: 8px; padding: 16px 14px; border-radius: 8px; margin-bottom: 7px; } +.project-item span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.project-item time { color: #697794; font-size: 13px; } +.project-item.selected { background: #edf4ff; color: var(--blue); } +.aside-empty { padding: 20px 12px; color: #98a2b3; } +.main-view { min-width: 0; flex: 1; } + +.project-page { min-height: 100vh; display: flex; flex-direction: column; } +.page-header { height: 80px; flex: 0 0 80px; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 0 32px; background: rgba(255,255,255,.95); position: sticky; top: 0; z-index: 3; } +.page-heading, .run-actions { display: flex; align-items: center; gap: 12px; } +.page-header h1 { margin: 0; font-size: 25px; letter-spacing: -.02em; } +.tag { display: inline-flex; align-items: center; height: 30px; padding: 0 11px; border: 1px solid #cfd7e4; border-radius: 6px; color: #52617b; font-size: 14px; font-weight: 500; white-space: nowrap; } +.tag.blue { color: var(--blue); border-color: #9dbdff; } +.tag.green { color: var(--green); border-color: #9be0bd; } +.work-scroll { width: min(920px, calc(100% - 64px)); margin: 0 auto; padding: 32px 0 72px; } +.history-loading { margin-top: 24vh; text-align: center; color: var(--muted); } + +.material-start { width: 640px; max-width: 100%; margin: 10vh auto 0; } +.material-start h2 { font-size: 24px; margin: 0 0 24px; } +.upload-box .el-upload-dragger { border: 1px dashed #a9b8cf; background: #fbfdff; padding: 44px; } +.upload-box .el-icon { color: var(--blue); font-size: 34px; } +.upload-box p { margin: 14px 0 4px; font-size: 16px; } +.upload-box small { color: #8995a8; } +.folder-upload { display: flex; justify-content: center; margin-top: 12px; } +.folder-upload input { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); } +.file-chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0; } +.file-chips span { display: inline-flex; align-items: center; gap: 6px; padding: 8px 11px; border: 1px solid var(--line); border-radius: 6px; font-size: 14px; } +.file-chips svg { width: 16px; color: var(--blue); } +.file-chips > small { align-self: center; color: var(--muted); } + +.timeline { display: flex; flex-direction: column; gap: 12px; } +.load-earlier { align-self: center; border: 0; background: transparent; color: var(--muted); cursor: pointer; padding: 8px 16px; } +.load-earlier:hover, .load-earlier:focus-visible { color: var(--primary); } +.flow-row { min-width: 0; content-visibility: auto; contain-intrinsic-size: 54px; } +.flow-message { display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 14px; margin: 0; } +.flow-message > .flow-content { grid-column: 2; } +.flow-tool, .flow-reasoning, .flow-notice { position: relative; padding-left: 54px; } +.agent-avatar { width: 38px; height: 38px; border-radius: 11px; background: #edf4ff; color: var(--blue); display: grid; place-items: center; } +.agent-avatar svg { width: 21px; height: 21px; stroke-width: 1.8; } +.flow-content { min-width: 0; } +.flow-meta { display: flex; gap: 10px; align-items: baseline; margin: 1px 0 8px; } +.flow-meta time { color: #6c7b95; font-size: 13px; } +.agent-markdown { min-width: 0; color: #253247; font-size: 15px; line-height: 1.75; overflow-wrap: anywhere; } +.agent-markdown > :first-child { margin-top: 0; } +.agent-markdown > :last-child { margin-bottom: 0; } +.agent-markdown p.paragraph-node { margin: 0; } +.agent-markdown > .node-slot + .node-slot { margin-top: 12px; } +.agent-markdown h1, .agent-markdown h2, .agent-markdown h3 { margin: 20px 0 10px; line-height: 1.35; color: #182235; } +.agent-markdown h1 { font-size: 21px; } +.agent-markdown h2 { font-size: 18px; } +.agent-markdown h3 { font-size: 16px; } +.agent-markdown ul, .agent-markdown ol { margin: 8px 0 12px; padding-left: 24px; } +.agent-markdown li + li { margin-top: 4px; } +.agent-markdown blockquote { margin: 12px 0; padding-left: 14px; border-left: 2px solid #d8e0eb; color: #5d687b; } +.agent-markdown code { padding: 2px 5px; border-radius: 4px; background: #f2f4f7; font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; } +.agent-markdown pre { margin: 12px 0; padding: 14px 16px; overflow-x: auto; border-radius: 7px; background: #f5f7fa; } +.agent-markdown pre code { padding: 0; background: transparent; } +.agent-markdown a { color: var(--blue); text-decoration: underline; text-underline-offset: 3px; } +.agent-markdown table { display: block; max-width: 100%; margin: 12px 0; overflow-x: auto; border-collapse: collapse; } +.agent-markdown th, .agent-markdown td { padding: 7px 10px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; } +.activity-row { color: #778195; font-size: 13px; border: 0; } +.activity-row summary { width: max-content; max-width: 100%; display: flex; align-items: center; gap: 8px; padding: 3px 0; cursor: pointer; list-style: none; } +.activity-row summary::-webkit-details-marker { display: none; } +.activity-row summary::after { content: "›"; margin-left: 2px; color: #a1a9b7; transition: transform .16s ease; } +.activity-row[open] summary::after { transform: rotate(90deg); } +.activity-row summary > svg { width: 15px; height: 15px; flex: 0 0 15px; color: currentColor; stroke-width: 1.8; } +.activity-row p { margin: 6px 0 2px 23px; color: #647084; font-size: 13px; line-height: 1.65; white-space: pre-wrap; } +.activity-row.failed { color: #b54747; } +.activity-row.active summary span { color: transparent; background: linear-gradient(90deg, #8d96a6 25%, #3f83ed 50%, #8d96a6 75%); background-size: 220% 100%; background-clip: text; animation: activity-shimmer 1.7s linear infinite; } +.view-image-strip { display: flex; flex-wrap: nowrap; gap: 10px; margin: 8px 0 4px 23px; overflow-x: auto; padding: 0 0 8px; } +.view-image-item { flex: 0 0 168px; min-width: 0; padding: 0; border: 0; color: #657187; background: transparent; text-align: left; cursor: zoom-in; } +.view-image-item:focus-visible { border-radius: 7px; outline: 2px solid var(--blue); outline-offset: 3px; } +.view-image-strip img { display: block; width: 168px; height: 98px; object-fit: cover; border-radius: 7px; background: #f4f6f8; } +.view-image-strip span { display: block; margin-top: 5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; } +.finalizing-row { margin-left: 54px; color: #778195; font-size: 13px; } +.finalizing-row span { color: transparent; background: linear-gradient(90deg, #8d96a6 25%, #3f83ed 50%, #8d96a6 75%); background-size: 220% 100%; background-clip: text; animation: activity-shimmer 1.7s linear infinite; } +@keyframes activity-shimmer { to { background-position: -220% 0; } } +@media (prefers-reduced-motion: reduce) { .activity-row.active summary span, .finalizing-row span { color: inherit; background: none; animation: none; } } +.notice-row { display: flex; align-items: center; gap: 9px; padding: 12px 14px; border-radius: 8px; background: #f6f9ff; } +.notice-row svg { width: 18px; } +.notice-row.success { color: #087d41; } +.notice-row.error { color: #c53131; background: #fff7f7; } +.notice-row.info { color: #45658f; background: #f7f9fc; } +.pending { opacity: .9; } + +.ask-card { width: 700px; max-width: calc(100% - 60px); margin: 28px 0 0 60px; padding: 22px; border-radius: 9px; background: #f6f9ff; box-shadow: inset 0 0 0 1px #d7e4fb; } +.ask-card h3 { color: var(--blue); margin: 0 0 5px; font-size: 20px; } +.ask-card > p { color: #697794; margin: 0 0 16px; font-size: 14px; } +.plan-fields { overflow: hidden; border-radius: 6px; background: #fff; box-shadow: inset 0 0 0 1px #dce4ef; } +.plan-fields label { display: grid; grid-template-columns: 150px 1fr; align-items: center; min-height: 52px; border-bottom: 1px solid var(--line); } +.plan-fields label:last-child { border: 0; } +.plan-fields label > span { padding-left: 16px; } +.plan-fields .el-input__wrapper { box-shadow: none; } +.plan-fields .el-input-number { width: 100%; } +.plan-fields .el-input-number .el-input__wrapper { box-shadow: none; } +.plan-summary { margin: 12px 0 16px; padding: 11px 14px; border-radius: 6px; color: #4b6188; background: #eaf2ff; } +.plan-note { display: block; margin-bottom: 16px; } +.plan-note > span { display: block; margin-bottom: 8px; color: #53617b; font-size: 14px; } +.ask-actions { display: flex; gap: 8px; } +.material-items { margin-bottom: 16px; overflow: hidden; border-radius: 7px; background: #fff; box-shadow: inset 0 0 0 1px #dce4ef; } +.material-item { min-height: 72px; display: grid; grid-template-columns: minmax(180px, 1fr) 190px 58px; gap: 10px; align-items: center; padding: 12px 14px; border-bottom: 1px solid var(--line); } +.material-item:last-child { border-bottom: 0; } +.material-item > div { min-width: 0; display: flex; flex-direction: column; gap: 5px; } +.material-item strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.material-item small { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.material-item small.field-error { color: #b42318; } +.material-upload { color: var(--blue); cursor: pointer; text-align: center; } +.material-upload.busy { color: var(--muted); } +.material-upload input { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); } +.material-clear { margin: 0; padding: 16px; color: var(--green); } +.material-more { width: 100%; padding: 11px; border: 0; border-top: 1px solid var(--line); background: #fff; color: var(--blue); cursor: pointer; } +.material-upload:focus-within, .material-more:focus-visible { outline: 2px solid var(--blue); outline-offset: -2px; } +.artifact-card { margin: 28px 0 min(28vh, 280px) 60px; border-radius: 8px; overflow: hidden; box-shadow: inset 0 0 0 1px #dce4ef; } +.artifact-row { display: grid; grid-template-columns: 32px 1fr auto; gap: 12px; align-items: center; padding: 16px 20px; border-bottom: 1px solid var(--line); } +.artifact-row:last-child { border: 0; } +.artifact-row > svg { width: 25px; color: var(--blue); } +.artifact-row div { display: flex; flex-direction: column; gap: 4px; } +.artifact-row small { color: #7b879b; } +.artifact-row a { color: var(--blue); } +.stream-error { display: block; border: 0; background: transparent; color: #c53131; margin: 24px auto; cursor: pointer; } +.retry-button { display: block; margin: 28px auto 0; } +.back-to-bottom { position: fixed; right: 32px; bottom: 28px; width: 38px; height: 38px; border: 0; border-radius: 50%; background: #fff; color: var(--blue); box-shadow: 0 6px 22px rgba(29, 58, 111, .14); cursor: pointer; } +.back-to-bottom:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; } +.empty-main { display: grid; place-items: center; min-height: 100vh; color: #8995a8; } + +.settings-page { min-height: 100vh; padding: 28px 42px; } +.settings-page > header h1 { margin: 0; font-size: 28px; } +.settings-page > header p { color: #5f6d86; margin: 10px 0 0; } +.settings-grid { display: grid; grid-template-columns: 380px minmax(520px, 1fr); margin-top: 38px; min-height: 740px; } +.settings-list { padding-right: 28px; border-right: 1px solid var(--line); } +.settings-list h2, .skill-list h2 { font-size: 18px; margin: 0 0 18px; } +.settings-list button { width: 100%; display: grid; grid-template-columns: 1fr auto; text-align: left; padding: 18px 16px; border: 0; border-radius: 7px; background: #fff; cursor: pointer; } +.settings-list button.selected { background: #edf4ff; color: var(--blue); } +.settings-list button strong, .settings-list button span { grid-column: 1; } +.settings-list button span { margin-top: 8px; color: #5f6d86; } +.settings-list button small { grid-column: 2; grid-row: 1 / span 2; align-self: end; color: var(--green); } +.settings-list button i, .skill-list button > i { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--green); margin-right: 6px; } +.settings-form { padding-left: 28px; } +.form-title { height: 62px; display: flex; align-items: start; justify-content: space-between; border-bottom: 1px solid var(--line); } +.form-title h2 { margin: 0; font-size: 22px; } +.settings-form > label { display: grid; grid-template-columns: 170px minmax(320px, 1fr); align-items: center; min-height: 88px; border-bottom: 1px solid var(--line); } +.capability-row { display: grid; grid-template-columns: 170px 1fr; min-height: 88px; align-items: center; border-bottom: 1px solid var(--line); } +.capability-row div { display: flex; gap: 8px; } +.capability-row b { padding: 6px 10px; border: 1px solid #d3dbe7; border-radius: 5px; font-size: 13px; font-weight: 500; } +.model-actions { display: flex; align-items: center; gap: 16px; padding-top: 28px; } +.connection-ok { color: var(--green); display: inline-flex; align-items: center; gap: 6px; } +.connection-ok svg { width: 18px; } + +.skills-header { display: flex; justify-content: space-between; align-items: start; } +.import-skill-trigger { display: inline-flex; align-items: center; gap: 8px; min-height: 32px; padding: 0 15px; border: 1px solid var(--line); border-radius: 8px; color: var(--text); background: #fff; cursor: pointer; } +.import-skill-trigger:hover, .skills-header .el-upload:focus-visible .import-skill-trigger { border-color: var(--primary); color: var(--primary); } +.skill-grid { display: grid; grid-template-columns: 480px minmax(540px, 1fr); margin-top: 24px; min-height: 780px; } +.skill-list { border-right: 1px solid var(--line); padding-right: 16px; overflow-y: auto; max-height: calc(100vh - 150px); } +.skill-item { min-height: 84px; display: grid; grid-template-columns: minmax(0, 1fr) 44px; align-items: center; border-bottom: 1px solid var(--line); background: #fff; } +.skill-item.selected { background: #edf4ff; } +.skill-select { min-width: 0; min-height: 84px; display: grid; grid-template-columns: minmax(0, 1fr) 52px 54px; align-items: center; gap: 8px; border: 0; background: transparent; text-align: left; padding: 14px; cursor: pointer; } +.skill-select > span { min-width: 0; display: flex; flex-direction: column; gap: 7px; } +.skill-select strong, .skill-select span > small { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.skill-select strong { color: #1f2a3d; } +.skill-select span > small { color: #667085; font-size: 13px; } +.skill-select > i { color: var(--green); font-style: normal; white-space: nowrap; } +.skill-select > i::before { content: ''; display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--green); margin-right: 5px; } +.skill-detail { padding-left: 28px; } +.skill-title { min-height: 72px; display: flex; justify-content: space-between; align-items: start; gap: 12px; } +.skill-title > div { min-width: 0; flex: 1; display: flex; align-items: center; gap: 8px; } +.skill-title h2 { margin: 0 6px 0 0; font-size: 24px; } +.skill-detail pre { min-height: 450px; max-height: calc(100vh - 280px); overflow: auto; white-space: pre-wrap; margin: 8px 0 0; padding: 22px; border-radius: 7px; background: #fafbfd; color: #293752; line-height: 1.7; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 14px; box-shadow: inset 0 0 0 1px #e1e7f0; } +.resource-list { display: flex; flex-direction: column; gap: 8px; } +.resource-list span { padding: 12px; border-bottom: 1px solid var(--line); } +.validation-ok { color: var(--green); } + +.login-page { min-height: 100vh; display: grid; place-items: center; background: #f8faff; } +.login-panel { width: 360px; padding: 36px; display: flex; flex-direction: column; gap: 16px; border-radius: 14px; background: #fff; box-shadow: 0 12px 44px rgba(34, 64, 120, .08); } +.login-panel .brand.large { margin: 0 auto; } +.login-panel h1 { margin: 4px 0 10px; text-align: center; font-size: 24px; } +.full-button { width: 100%; } +.form-error { color: #c53131; font-size: 13px; margin: 0; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } + +.el-button--primary { --el-button-bg-color: var(--blue); --el-button-border-color: var(--blue); } +.el-input__wrapper, .el-textarea__inner { box-shadow: inset 0 0 0 1px #d9e0ea; } +.el-dialog { border-radius: 12px; } + +@media (max-width: 1180px) { + .project-list { width: 240px; flex-basis: 240px; } + .settings-page { padding-left: 28px; padding-right: 28px; } + .settings-grid { grid-template-columns: 310px 1fr; } + .skill-grid { grid-template-columns: 390px 1fr; } + .skill-title { min-height: 100px; } + .skill-title > div { align-items: flex-start; flex-wrap: wrap; } + .skill-title h2 { flex-basis: 100%; font-size: 21px; overflow-wrap: anywhere; } +} + +@media (max-width: 720px) { + .rail { width: 64px; flex-basis: 64px; padding-left: 0; padding-right: 0; } + .rail a { width: 52px; font-size: 12px; } + .project-list { width: 190px; flex-basis: 190px; padding: 20px 10px; } + .work-scroll { width: calc(100% - 32px); } + .page-header { padding: 0 16px; } + .page-header h1 { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 20px; } + .ask-card, .artifact-card { max-width: 100%; margin-left: 0; } + .flow-tool, .flow-reasoning, .flow-notice { padding-left: 28px; } + .flow-tool::before, .flow-reasoning::before { left: 7px; } + .flow-tool::after, .flow-reasoning::after { left: 4px; } + .material-item { grid-template-columns: 1fr 160px; } + .material-upload { grid-column: 2; } + .settings-page { padding: 24px 16px; } + .settings-grid, .skill-grid { grid-template-columns: 1fr; } + .settings-list, .skill-list { max-height: 300px; border-right: 0; border-bottom: 1px solid var(--line); padding: 0 0 20px; } + .settings-form, .skill-detail { padding: 24px 0 0; } + .settings-form > label, .capability-row { grid-template-columns: 130px 1fr; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } +} diff --git a/web-ui/tsconfig.app.json b/web-ui/tsconfig.app.json new file mode 100644 index 0000000..c94ec65 --- /dev/null +++ b/web-ui/tsconfig.app.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "useDefineForClassFields": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "jsx": "preserve", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "skipLibCheck": true, + "esModuleInterop": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["vite/client"] + }, + "include": ["src/**/*.ts", "src/**/*.vue"] +} diff --git a/web-ui/tsconfig.json b/web-ui/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/web-ui/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/web-ui/tsconfig.node.json b/web-ui/tsconfig.node.json new file mode 100644 index 0000000..2949cb2 --- /dev/null +++ b/web-ui/tsconfig.node.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "composite": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true + }, + "include": ["vite.config.ts"] +} diff --git a/web-ui/vite.config.ts b/web-ui/vite.config.ts new file mode 100644 index 0000000..55d565c --- /dev/null +++ b/web-ui/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +export default defineConfig({ + plugins: [vue()], + server: { + port: 5173, + proxy: { + '/api': 'http://127.0.0.1:8080' + } + }, + build: { + target: 'es2022', + sourcemap: true, + rollupOptions: { + output: { + manualChunks: { vue: ['vue', 'vue-router'] } + } + } + } +})