diff --git a/.vscode/settings.json b/.vscode/settings.json index a17b7294..4f91fcd0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,5 +2,8 @@ // MyBatis-Plus 方法引用会触发 Eclipse 空值分析误报;关闭后无需每类加 @SuppressWarnings("null") "java.compile.nullAnalysis.mode": "disabled", // pom 变更(如 Boot 升级)后自动刷新 classpath,避免 Eclipse「class file was not written / project inconsistent」 - "java.configuration.updateBuildConfiguration": "automatic" -} \ No newline at end of file + "java.configuration.updateBuildConfiguration": "automatic", + // Agent(唯一 Python 子项目)用本地 venv,避免 Pylance 解析不到 langchain 等依赖 + "python.defaultInterpreterPath": "${workspaceFolder}/apps/agent/.venv/bin/python", + "python.analysis.extraPaths": ["${workspaceFolder}/apps/agent"] +} diff --git a/apps/agent/.env.dev b/apps/agent/.env.dev new file mode 100644 index 00000000..f787d50d --- /dev/null +++ b/apps/agent/.env.dev @@ -0,0 +1,18 @@ +# 本地开发(AGENT_ENV=dev,默认) +# 可另建 gitignore 的 .env 覆盖本文件中的密钥 + +JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security +MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev +MONGO_DB=ecom_dmb_agent_dev +# 与 Server application-dev 同 Redis DB=2 +REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2 +SERVER_BASE_URL=http://localhost:8080 +LLM_FALLBACK_ENABLED=true +LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1 +LLM_FALLBACK_API_KEY= +LLM_FALLBACK_MODEL=deepseek-chat +CORS_ORIGINS=http://localhost:5173,http://localhost:5666 +MCP_BASE_URL=http://localhost:8080/mcp +MCP_BEARER_TOKEN=dev-agent-mcp-token +MCP_TOOLS_ENABLED=true +PORT=8200 diff --git a/apps/agent/.env.example b/apps/agent/.env.example index cca70787..21061772 100644 --- a/apps/agent/.env.example +++ b/apps/agent/.env.example @@ -1,7 +1,19 @@ +# Agent 环境配置说明 +# +# 按 AGENT_ENV 加载对应文件(与后端 Spring profile 对齐): +# AGENT_ENV=dev → .env.dev (本地默认) +# AGENT_ENV=test → .env.test +# AGENT_ENV=pre → .env.pre +# AGENT_ENV=prod → .env.prod +# +# 本地也可再建 gitignore 的 .env,会覆盖同名变量(便于放真实 Key)。 +# 部署时 compose 注入 AGENT_ENV=test|pre|prod,并挂载对应 .env.{env}。 +# +# Redis:与同环境 Server 共用同一 Redis DB,读缓存键 agent:llm:rt:* + JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev MONGO_DB=ecom_dmb_agent_dev -# 与 Server 同 Redis DB,共享 agent:llm:rt:* 缓存 REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2 SERVER_BASE_URL=http://localhost:8080 LLM_FALLBACK_ENABLED=true diff --git a/apps/agent/.env.pre b/apps/agent/.env.pre new file mode 100644 index 00000000..bd9edc3d --- /dev/null +++ b/apps/agent/.env.pre @@ -0,0 +1,17 @@ +# 预发环境(AGENT_ENV=pre,端口 8202) +# 与 Server application-pre 对齐:Redis DB=0、后端 8102 + +JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security +MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent_pre +MONGO_DB=ecom_dmb_agent_pre +REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0 +SERVER_BASE_URL=http://192.168.3.101:8102 +LLM_FALLBACK_ENABLED=false +LLM_FALLBACK_BASE_URL= +LLM_FALLBACK_API_KEY= +LLM_FALLBACK_MODEL= +CORS_ORIGINS=https://cd.newloop.top +MCP_BASE_URL=http://192.168.3.101:8102/mcp +MCP_BEARER_TOKEN= +MCP_TOOLS_ENABLED=true +PORT=8202 diff --git a/apps/agent/.env.prod b/apps/agent/.env.prod new file mode 100644 index 00000000..2edc43dc --- /dev/null +++ b/apps/agent/.env.prod @@ -0,0 +1,17 @@ +# 生产环境(AGENT_ENV=prod,端口 8203) +# 与 Server application-prod 对齐:Redis DB=0、后端 8103 + +JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security +MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent +MONGO_DB=ecom_dmb_agent +REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0 +SERVER_BASE_URL=http://192.168.3.101:8103 +LLM_FALLBACK_ENABLED=false +LLM_FALLBACK_BASE_URL= +LLM_FALLBACK_API_KEY= +LLM_FALLBACK_MODEL= +CORS_ORIGINS=https://cd.newloop.top +MCP_BASE_URL=http://192.168.3.101:8103/mcp +MCP_BEARER_TOKEN= +MCP_TOOLS_ENABLED=true +PORT=8203 diff --git a/apps/agent/.env.test b/apps/agent/.env.test new file mode 100644 index 00000000..fc541b94 --- /dev/null +++ b/apps/agent/.env.test @@ -0,0 +1,17 @@ +# 测试环境(AGENT_ENV=test,端口 8201) +# 与 Server application-test 对齐:Redis DB=3、后端 8101 + +JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security +MONGO_URI=mongodb://ecom_dmb_agent_test:ecom_dmb_agent_test@192.168.3.100:27017/?authSource=ecom_dmb_agent_test +MONGO_DB=ecom_dmb_agent_test +REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/3 +SERVER_BASE_URL=http://192.168.3.101:8101 +LLM_FALLBACK_ENABLED=false +LLM_FALLBACK_BASE_URL= +LLM_FALLBACK_API_KEY= +LLM_FALLBACK_MODEL= +CORS_ORIGINS=https://cd.newloop.top,http://localhost:5666 +MCP_BASE_URL=http://192.168.3.101:8101/mcp +MCP_BEARER_TOKEN= +MCP_TOOLS_ENABLED=true +PORT=8201 diff --git a/apps/agent/README.md b/apps/agent/README.md index 5481a01b..c8d1018a 100644 --- a/apps/agent/README.md +++ b/apps/agent/README.md @@ -9,7 +9,7 @@ cd apps/agent python -m venv .venv source .venv/bin/activate pip install -r requirements.txt -cp .env.example .env # JWT_SECRET / Mongo / Redis(与 Server 同库) / SERVER_BASE_URL / MCP +# 默认 AGENT_ENV=dev,加载 .env.dev;也可 cp .env.dev .env 做本地覆盖 uvicorn api.main:app --reload --host 0.0.0.0 --port 8200 ``` @@ -18,13 +18,27 @@ API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/age **模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(凭证 + 多模型勾选;`POST .../probe-models` 拉目录);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉**默认模型**明文注入。 +## 分环境配置 + +与后端 `application-{profile}.yml` 对应,由 `AGENT_ENV` 选择文件: + +| AGENT_ENV | 配置文件 | 端口 | Redis DB(对齐 Server) | +|-----------|----------|------|-------------------------| +| `dev`(默认) | `.env.dev` | 8200 | 2 | +| `test` | `.env.test` | 8201 | 3 | +| `pre` | `.env.pre` | 8202 | 0 | +| `prod` | `.env.prod` | 8203 | 0 | + +若存在 gitignore 的 `.env`,仅在 `AGENT_ENV=dev` 时覆盖同名变量。部署时 compose 注入 `AGENT_ENV=test|pre|prod`。 + ## 环境变量要点 | 变量 | 说明 | |------|------| +| `AGENT_ENV` | 选择 `.env.{env}` | | `JWT_SECRET` | 与 Java `jwt.secret` 一致 | | `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory) | -| `REDIS_URL` | **与 Server 同 DB**,读 LLM 运行时缓存 | +| `REDIS_URL` | **与同环境 Server 同 DB**,读 LLM 运行时缓存 `agent:llm:rt:*` | | `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime` | | `MCP_BASE_URL` / `MCP_BEARER_TOKEN` | 调 Server `/mcp`,并带 `X-Agent-Company-Id` / `X-Agent-User-Id` | | `LLM_FALLBACK_*` | 仅本地:公司未配置时的 OpenAI Compatible fallback | diff --git a/apps/agent/config/settings.py b/apps/agent/config/settings.py index 73f634cc..f24c1744 100644 --- a/apps/agent/config/settings.py +++ b/apps/agent/config/settings.py @@ -1,14 +1,46 @@ -"""应用配置(环境变量)。""" +"""应用配置:按 AGENT_ENV 加载 .env.{env},环境变量优先。""" +from __future__ import annotations + +import os from functools import lru_cache +from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict +# 与后端 Spring profile 对齐:dev | test | pre | prod +_AGENT_ENV = (os.getenv("AGENT_ENV") or "dev").strip().lower() or "dev" + + +def _resolve_env_files() -> tuple[str, ...]: + """加载 .env.{AGENT_ENV};仅 dev 额外允许 .env 覆盖(本机密钥)。""" + files: list[str] = [] + profile = Path(f".env.{_AGENT_ENV}") + if profile.is_file(): + files.append(str(profile)) + if _AGENT_ENV == "dev": + local = Path(".env") + if local.is_file(): + files.append(str(local)) + if not files: + # 兼容:尚无分环境文件时回退 .env + if Path(".env").is_file(): + files.append(".env") + else: + files.append(f".env.{_AGENT_ENV}") + return tuple(files) + class Settings(BaseSettings): - model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") + model_config = SettingsConfigDict( + env_file=_resolve_env_files(), + env_file_encoding="utf-8", + extra="ignore", + ) app_name: str = "ecom-dmb-agent" + # 当前环境名(只读展示;实际由 AGENT_ENV 决定加载哪个文件) + agent_env: str = _AGENT_ENV host: str = "0.0.0.0" port: int = 8200 cors_origins: str = "http://localhost:5173,http://localhost:5666" @@ -20,14 +52,14 @@ class Settings(BaseSettings): mongo_uri: str = "mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev" mongo_db: str = "ecom_dmb_agent_dev" - # 须与 Server Redis 同库,才能命中 agent:llm:rt:{companyId} + # 须与同环境 Server Redis 同库,才能命中 agent:llm:rt:* 缓存 redis_url: str = "redis://:redis_qinghua@192.168.3.100:6379/2" llm_cache_ttl_seconds: int = 600 # Java Server 根地址(内部拉 LLM 运行时) server_base_url: str = "http://localhost:8080" - # 仅本地开发:公司未配置时的 fallback(生产勿用) + # 仅本地开发:公司未配置时的 fallback(test/pre/prod 应关闭) llm_fallback_enabled: bool = True llm_fallback_base_url: str = "https://api.openai.com/v1" llm_fallback_api_key: str = "" diff --git a/apps/agent/deploy/Dockerfile b/apps/agent/deploy/Dockerfile new file mode 100644 index 00000000..3c999c9b --- /dev/null +++ b/apps/agent/deploy/Dockerfile @@ -0,0 +1,14 @@ +# 运行时镜像:业务代码与依赖通过 volume 挂载 /app,更新部署无需重建镜像 +ARG BASE_IMAGE=docker.m.daocloud.io/library/python:3.12-slim +FROM ${BASE_IMAGE} + +WORKDIR /app +RUN groupadd --system app && useradd --system --gid app --home-dir /app app + +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +USER app +# 实际端口由环境 PORT 决定(test:8201 / pre:8202 / prod:8203) +EXPOSE 8201 8202 8203 +ENTRYPOINT ["/entrypoint.sh"] diff --git a/apps/agent/deploy/entrypoint.sh b/apps/agent/deploy/entrypoint.sh new file mode 100755 index 00000000..eb5f380f --- /dev/null +++ b/apps/agent/deploy/entrypoint.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# 使用镜像内 Python 加载挂载的源码与 .deps(避免 venv shebang 路径不可移植) +set -e +export PYTHONPATH="/app:/app/.deps${PYTHONPATH:+:$PYTHONPATH}" +exec python -m uvicorn api.main:app --host 0.0.0.0 --port "${PORT:-8201}" diff --git a/apps/agent/pyrightconfig.json b/apps/agent/pyrightconfig.json new file mode 100644 index 00000000..513431c7 --- /dev/null +++ b/apps/agent/pyrightconfig.json @@ -0,0 +1,9 @@ +{ + "include": ["."], + "exclude": [".venv", "**/__pycache__"], + "venvPath": ".", + "venv": ".venv", + "pythonVersion": "3.12", + "pythonPlatform": "Linux", + "extraPaths": ["."] +} diff --git a/deploy/MANUAL-DEPLOY.md b/deploy/MANUAL-DEPLOY.md index a77ffed6..1ad8ddc7 100644 --- a/deploy/MANUAL-DEPLOY.md +++ b/deploy/MANUAL-DEPLOY.md @@ -2,28 +2,28 @@ 部署采用 **运行时镜像 + 目录挂载** 模式: -- **首次部署**:在服务器构建一次运行时镜像(仅 JRE/Node 环境,不含业务代码),启动容器并挂载 `app/` 目录。 +- **首次部署**:在服务器构建一次运行时镜像(仅 JRE/Node/Python 环境,不含业务代码),启动容器并挂载 `app/` 目录。 - **后续更新**:只需上传编译产物到 `app/`,然后 **重启容器**,无需重新 `docker build`。 ## 远程目录结构 `deployPath` 为部署根目录。 -**后端 / 授权(Docker)**: +**后端 / 授权 / 智能体(Docker)**: ``` {deployPath}/ecom-dmb/{service}/{env}/ ├── docker-compose.yml ├── Dockerfile +├── entrypoint.sh # 仅 agent └── app/ - ├── app.jar # 每次部署更新 - ├── application-{profile}.yml # 环境配置(与 jar 同级,首次从仓库初始化) + ├── app.jar # 后端:每次部署更新 + ├── application-{profile}.yml # 后端环境配置(首次从仓库初始化) ├── config/ # license、渠道配置等 - │ ├── channel-pdd.yml - │ ├── license.key - │ └── revoked.jti ├── uploads/ # 本地上传文件(持久化,部署不覆盖) - └── static/ # 静态资源(含 extension-features,部署合并同步) + ├── static/ # 静态资源 + ├── dist/ + node_modules/ # 授权 + ├── api/ … + .deps/ + .env.{env} # 智能体(按 AGENT_ENV 加载;首次播种,后续保留) ``` **前端(静态,用目录名区分环境)**: @@ -42,9 +42,10 @@ /opt/ecom-dmb/backend/test/app/static/ /opt/ecom-dmb-test/index/ # 前端站点根 /opt/ecom-dmb/license/test/app/ +/opt/ecom-dmb/agent/test/app/ ``` -Docker 资源名同样带环境后缀:`ecom-backend-test` / `ecom-backend-prod` 等。 +Docker 资源名同样带环境后缀:`ecom-backend-test` / `ecom-agent-test` 等。 本地编译产物统一放在 `deploy/artifacts/`(已 gitignore): @@ -52,7 +53,8 @@ Docker 资源名同样带环境后缀:`ecom-backend-test` / `ecom-backend-prod artifacts/ ├── frontend/ # 前端 dist 静态文件 ├── backend/ # app.jar + static/ -└── license/ # dist、package.json、node_modules 等 +├── license/ # dist、package.json、node_modules 等 +└── agent/ # 源码 + .deps(pip --target) ``` --- @@ -72,7 +74,7 @@ pnpm dev | 仅编译 | 只编译到 `artifacts/`,不上传 | | 仅上传重启 | 从 `artifacts/` 上传并重启,不重新编译 | -服务范围可选「全部」或「指定服务…」(空格多选)。子菜单按 **← 左方向键** 返回上一步。 +服务范围可选「全部」或「指定服务…」(空格多选,含智能体)。子菜单按 **← 左方向键** 返回上一步。 --- @@ -106,6 +108,19 @@ cd ../../../deploy/artifacts/license pnpm install --prod --frozen-lockfile ``` +**智能体** + +```bash +# 推荐用 TUI「仅编译」;手动等价步骤: +mkdir -p deploy/artifacts/agent +# 同步 api/ agent/ application/ config/ domain/ infrastructure/ requirements.txt +# (排除 .venv、.env、__pycache__) +cd deploy/artifacts/agent +python3 -m pip install -r requirements.txt --target .deps --upgrade +``` + +> `.deps` 须在与服务器相同的 OS/架构(glibc Linux x86_64)上安装,以便与 `python:3.12-slim` 运行时匹配。 + ### 2. 上传到服务器 **后端**(根目录 `/opt`,test 环境): @@ -129,6 +144,21 @@ scp license.tar.gz user@host:/opt/ecom-dmb/license/test/ ssh user@host 'cd /opt/ecom-dmb/license/test && rm -rf app/* && mkdir -p app && tar -xzf license.tar.gz -C app && rm license.tar.gz' ``` +**智能体**: + +```bash +# 若已有 .env,先备份再解压,避免被清空 +tar -czf agent.tar.gz -C artifacts/agent . +scp agent.tar.gz user@host:/opt/ecom-dmb/agent/test/ +ssh user@host 'cd /opt/ecom-dmb/agent/test && \ + (ls app/.env* >/dev/null 2>&1 && mkdir -p /tmp/agent-env.bak && cp -a app/.env* /tmp/agent-env.bak/ || true) && \ + rm -rf app/* && mkdir -p app && tar -xzf agent.tar.gz -C app && rm agent.tar.gz && \ + (test -d /tmp/agent-env.bak && cp -a /tmp/agent-env.bak/.env* app/ && rm -rf /tmp/agent-env.bak || \ + cp /path/to/.env.test app/.env.test)' +``` + +首次部署后编辑 `app/.env.{env}`(如 `.env.test`):`JWT_SECRET` 须与 Java 一致;`REDIS_URL` 与同环境 Server 同 Redis DB;`SERVER_BASE_URL` / `MCP_BASE_URL` 指向内网后端。容器通过 `AGENT_ENV=test|pre|prod` 选择配置文件。 + **前端**(静态目录,按环境后缀区分): ```bash @@ -137,7 +167,7 @@ scp frontend.tar.gz user@host:/opt/ecom-dmb-test/ ssh user@host 'cd /opt/ecom-dmb-test && rm -rf index && mkdir index && tar -xzf frontend.tar.gz -C index && rm frontend.tar.gz' ``` -Nginx 站点根目录一般为 `/opt/ecom-dmb-{env}/index`(如 test → `/opt/ecom-dmb-test/index`)。 +Nginx 站点根目录一般为 `/opt/ecom-dmb-{env}/index`(如 test → `/opt/ecom-dmb-test/index`)。网关把 `/api/agent` 反代到 Agent 端口。 ### 3. 重启容器 @@ -146,19 +176,26 @@ Nginx 站点根目录一般为 `/opt/ecom-dmb-{env}/index`(如 test → `/opt/ ssh user@192.168.3.101 cd /opt/ecom-dmb/backend/test docker compose -p ecom-backend-test up -d ecom-backend-test + +# 智能体 +cd /opt/ecom-dmb/agent/test +docker compose -p ecom-agent-test up -d ecom-agent-test +docker compose -p ecom-agent-test restart ecom-agent-test ``` -各环境容器名:`ecom-backend-test` / `ecom-backend-pre` / `ecom-backend-prod` +各环境容器名:`ecom-backend-test` / `ecom-backend-pre` / `ecom-backend-prod`;Agent 同理 `ecom-agent-*`。 --- ## 端口对照 -| 环境 | Spring Profile | 端口 | -|------|----------------|------| -| test | test | 8101 | -| pre | pre | 8102 | -| prod | prod | 8103 | +| 环境 | Spring Profile | 后端端口 | Agent 端口 | +|------|----------------|----------|------------| +| test | test | 8101 | 8201 | +| pre | pre | 8102 | 8202 | +| prod | prod | 8103 | 8203 | + +本机开发 Agent 仍用 `8200`。 --- @@ -167,7 +204,7 @@ docker compose -p ecom-backend-test up -d ecom-backend-test 使用 TUI **自动部署** 或 **上传产物并重启** 即可自动完成: 1. 上传产物到 `{deployPath}/ecom-dmb/{service}/{env}/app/` -2. 构建运行时 Dockerfile 镜像 +2. 构建运行时 Dockerfile 镜像(Agent 含 `entrypoint.sh`) 3. 在同目录生成 docker-compose.yml 并启动容器 若需手动初始化后端运行时镜像: @@ -178,12 +215,21 @@ docker build -t ecom-backend-test:latest . docker compose -p ecom-backend-test up -d ecom-backend-test ``` +Agent: + +```bash +cd /opt/ecom-dmb/agent/test +# 目录内需有 Dockerfile 与 entrypoint.sh +docker build -t ecom-agent-test:latest . +docker compose -p ecom-agent-test up -d ecom-agent-test +``` + --- ## 常见问题 **Q: 更新后代码没生效?** -确认已上传新产物并执行了 **restart**(TUI 自动部署会在 `up -d` 后再 `restart`)。仅 `docker compose up -d` 在 compose 未变时**不会**重启 JVM,挂载的 `app.jar` 替换后旧进程仍跑旧字节码。 +确认已上传新产物并执行了 **restart**(TUI 自动部署会在 `up -d` 后再 `restart`)。仅 `docker compose up -d` 在 compose 未变时**不会**重启 JVM,挂载的 `app.jar` 替换后旧进程仍跑旧字节码。Agent 同理需 restart 才能加载新 `.py` / `.deps`。 **Q: 登录报 jjwt Serializer / ServiceLoader?** 磁盘上的 fat jar 通常已含 `jjwt-impl`/`jjwt-jackson`;多见于容器未 restart,或 Spring Boot fat jar 下 ServiceLoader 未扫到嵌套 lib。后端已在 `JwtUtils` 显式绑定 Jackson;部署后务必 restart。 @@ -191,8 +237,12 @@ docker compose -p ecom-backend-test up -d ecom-backend-test **Q: 修改了 package.json(license)?** 需重新本地 `pnpm install --prod` 后再上传整个 `artifacts/license/` 目录。 +**Q: 修改了 requirements.txt(agent)?** +需重新本地 `pip install --target .deps`(TUI「仅编译」/「自动部署」会做)后再上传整个 `artifacts/agent/`。 + **Q: 想强制重建运行时镜像?** ```bash docker rmi ecom-backend-test:latest +# 或 docker rmi ecom-agent-test:latest # 再执行一次自动部署即可重新 init ``` diff --git a/deploy/config.example.json b/deploy/config.example.json index 185dd68e..1fd39eab 100644 --- a/deploy/config.example.json +++ b/deploy/config.example.json @@ -120,6 +120,40 @@ "nodeEnv": "prod", "licenseDbUrl": "" } + }, + "agent": { + "test": { + "server": { + "host": "192.168.3.101", + "port": 22, + "username": "root", + "deployPath": "/opt", + "authType": "key", + "keyPath": "/home/qinghua/.ssh/ecom-deploy" + }, + "port": 8201 + }, + "pre": { + "server": { + "host": "192.168.3.101", + "port": 22, + "username": "root", + "deployPath": "/opt", + "authType": "key", + "keyPath": "/home/qinghua/.ssh/ecom-deploy" + }, + "port": 8202 + }, + "prod": { + "server": { + "host": "agent.prod.com", + "port": 22, + "username": "root", + "deployPath": "/opt", + "authType": "password" + }, + "port": 8203 + } } } -} \ No newline at end of file +} diff --git a/deploy/src/artifacts.ts b/deploy/src/artifacts.ts index 74e947c0..f0b10681 100644 --- a/deploy/src/artifacts.ts +++ b/deploy/src/artifacts.ts @@ -8,7 +8,7 @@ import { ensureRemoteDir, execRemote, uploadFile } from './ssh.js'; import { printInfo } from './ui/render.js'; import type { Service } from './types.js'; -const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license']; +const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license', 'agent']; /** 确保 artifacts 根目录及子目录存在 */ export function ensureArtifactsDirs(): void { @@ -50,6 +50,13 @@ export function syncLicenseArtifacts(srcDir: string): string { return getArtifactDir('license'); } +/** 同步 Agent 源码到 artifacts/agent */ +export function syncAgentArtifacts(srcDir: string): string { + clearArtifactDir('agent'); + cpSync(srcDir, getArtifactDir('agent'), { recursive: true }); + return getArtifactDir('agent'); +} + /** 部署前检查本地产物是否就绪 */ export function assertArtifactsExist(service: Service): void { const dir = getArtifactDir(service); @@ -64,6 +71,16 @@ export function assertArtifactsExist(service: Service): void { return; } + if (service === 'agent') { + if (!existsSync(join(dir, 'requirements.txt')) || !existsSync(join(dir, 'api'))) { + throw new Error(`Agent 产物不完整: ${dir},请先编译智能体`); + } + if (!existsSync(join(dir, '.deps'))) { + throw new Error(`缺少 ${join(dir, '.deps')},请先编译智能体以安装依赖`); + } + return; + } + const files = readdirSync(dir); if (files.length === 0) { throw new Error(`产物目录为空: ${dir},请先编译 ${service}`); diff --git a/deploy/src/config.ts b/deploy/src/config.ts index aba96843..f0e44cbf 100644 --- a/deploy/src/config.ts +++ b/deploy/src/config.ts @@ -44,14 +44,35 @@ function defaultConfig(): DeployConfig { pre: { ...defaultServiceConfig('192.168.1.101', 3100), nodeEnv: 'pre', licenseDbUrl: '' }, prod: { ...defaultServiceConfig('license.prod.com', 3100), nodeEnv: 'prod', licenseDbUrl: '' }, }, + agent: { + test: defaultServiceConfig('192.168.3.101', 8201), + pre: defaultServiceConfig('192.168.3.101', 8202), + prod: defaultServiceConfig('agent.prod.com', 8203), + }, }, }; } +/** 旧 config.json 缺服务时补默认项并写回 */ +function mergeMissingServices(cfg: DeployConfig): { config: DeployConfig; dirty: boolean } { + const defaults = defaultConfig(); + let dirty = false; + for (const service of Object.keys(defaults.services) as Service[]) { + if (!cfg.services[service]) { + cfg.services[service] = defaults.services[service]; + dirty = true; + } + } + return { config: cfg, dirty }; +} + export async function loadConfig(): Promise { try { const raw = await readFile(CONFIG_PATH, 'utf8'); - return JSON.parse(raw) as DeployConfig; + const parsed = JSON.parse(raw) as DeployConfig; + const { config, dirty } = mergeMissingServices(parsed); + if (dirty) await saveConfig(config); + return config; } catch { const cfg = defaultConfig(); await saveConfig(cfg); @@ -169,6 +190,18 @@ export function resolveBackendPort(env: Environment): number { } } +/** Agent 各环境监听端口(开发本机仍用 8200) */ +export function resolveAgentPort(env: Environment): number { + switch (env) { + case 'test': + return 8201; + case 'pre': + return 8202; + case 'prod': + return 8203; + } +} + /** 部署环境 pre 对应 Spring profile pre(application-pre.yml) */ export function resolveSpringProfile(profile?: string): string { return profile || 'prod'; @@ -224,6 +257,10 @@ export function getLicenseDir(): string { return join(PROJECT_ROOT, 'apps', 'license-server'); } +export function getAgentDir(): string { + return join(PROJECT_ROOT, 'apps', 'agent'); +} + export function getFrontendDeployDir(): string { return join(PROJECT_ROOT, 'apps', 'web', 'deploy'); } @@ -235,3 +272,7 @@ export function getBackendDeployDir(): string { export function getLicenseDeployDir(): string { return join(PROJECT_ROOT, 'apps', 'license-server', 'deploy'); } + +export function getAgentDeployDir(): string { + return join(PROJECT_ROOT, 'apps', 'agent', 'deploy'); +} diff --git a/deploy/src/deploy/agent.ts b/deploy/src/deploy/agent.ts new file mode 100644 index 00000000..5db6a4e6 --- /dev/null +++ b/deploy/src/deploy/agent.ts @@ -0,0 +1,132 @@ +import { execSync } from 'child_process'; +import { existsSync, mkdirSync, rmSync } from 'fs'; +import { join } from 'path'; + +import { Client } from 'ssh2'; +import { syncAgentArtifacts, uploadArtifactDirectory } from '../artifacts.js'; +import { getAgentDir, getArtifactDir, getRemoteAppDir } from '../config.js'; +import { copyBuildArtifacts, getLocalTempPath } from '../platform.js'; +import { ensureRemoteDir, execRemote, uploadFile } from '../ssh.js'; +import { printInfo, printSuccess } from '../ui/render.js'; +import type { Environment, Service, ServiceEnvConfig } from '../types.js'; + +export const serviceType: Service = 'agent'; + +/** 同步到产物的源码目录(不含 .venv / .env*) */ +const AGENT_SOURCE_DIRS = [ + 'api', + 'agent', + 'application', + 'config', + 'domain', + 'infrastructure', +] as const; + +/** + * 「编译」:同步源码到 artifacts/agent,并 pip install --target .deps + * (用系统 python -m uvicorn 加载,避免 venv shebang 路径不可移植) + */ +export async function build(): Promise { + const agentDir = getAgentDir(); + if (!existsSync(agentDir)) throw new Error(`Agent 项目目录不存在: ${agentDir}`); + if (!existsSync(join(agentDir, 'requirements.txt'))) { + throw new Error(`缺少 requirements.txt: ${agentDir}`); + } + + printInfo('同步 Agent 源码...'); + const tmpDir = getLocalTempPath('ecom-agent-build'); + if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true }); + mkdirSync(tmpDir, { recursive: true }); + + for (const dir of AGENT_SOURCE_DIRS) { + copyBuildArtifacts(join(agentDir, dir), join(tmpDir, dir)); + } + copyBuildArtifacts(join(agentDir, 'requirements.txt'), join(tmpDir, 'requirements.txt')); + + // 去掉缓存,避免打进产物 + execSync( + `find "${tmpDir}" -type d \\( -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name .ruff_cache \\) -exec rm -rf {} + 2>/dev/null || true`, + ); + + const artifactDir = syncAgentArtifacts(tmpDir); + rmSync(tmpDir, { recursive: true, force: true }); + + printInfo('安装 Agent 依赖到 .deps(pip --target)...'); + execSync('python3 -m pip install -r requirements.txt --target .deps --upgrade', { + stdio: 'inherit', + cwd: artifactDir, + shell: process.platform === 'win32' ? (process.env.COMSPEC || 'cmd.exe') : undefined, + }); + + printSuccess(`Agent 构建完成,产物: ${artifactDir}`); + return artifactDir; +} + +/** 远程环境配置文件名:.env.test / .env.pre / .env.prod */ +function remoteEnvFileName(env: Environment): string { + return `.env.${env}`; +} + +/** 首次部署:若远程尚无 .env.{env},从仓库模板初始化(后续部署不覆盖) */ +async function seedRemoteEnvIfMissing( + conn: Client, + remoteAppDir: string, + env: Environment, +): Promise { + const name = remoteEnvFileName(env); + const remoteEnv = `${remoteAppDir}/${name}`; + const { code } = await execRemote(conn, `test -f "${remoteEnv}"`); + if (code === 0) return; + + const local = join(getAgentDir(), name); + if (!existsSync(local)) { + printInfo(`远程尚无 ${name},且本地无模板 ${local},请手动创建`); + return; + } + await uploadFile(conn, local, remoteEnv); + printInfo(`已初始化配置(仅首次): ${remoteEnv},请按环境核对 JWT/Mongo/Redis/Server`); +} + +/** + * 上传前备份远程全部 .env*,清空上传后恢复,避免密钥被制品覆盖。 + */ +async function preserveRemoteEnvAroundUpload( + conn: Client, + remoteAppDir: string, + env: Environment, + upload: () => Promise, +): Promise { + const bakDir = `/tmp/ecom-agent-env-${Date.now()}`; + await execRemote( + conn, + `mkdir -p "${bakDir}" && sh -c 'cd "${remoteAppDir}" && ls -A .env* >/dev/null 2>&1 && cp -a .env* "${bakDir}/" || true'`, + ); + + await upload(); + + const { code } = await execRemote(conn, `ls -A "${bakDir}"/.env* >/dev/null 2>&1`); + if (code === 0) { + await execRemote(conn, `cp -a "${bakDir}"/.env* "${remoteAppDir}/" && rm -rf "${bakDir}"`); + } else { + await execRemote(conn, `rm -rf "${bakDir}"`); + await seedRemoteEnvIfMissing(conn, remoteAppDir, env); + } +} + +/** 上传 artifacts/agent 到远程挂载目录 */ +export async function deploy( + conn: Client, + cfg: ServiceEnvConfig, + _buildDir: string, + env: Environment, +): Promise { + const artifactDir = getArtifactDir('agent'); + const remoteAppDir = getRemoteAppDir(cfg, 'agent', env); + await ensureRemoteDir(conn, remoteAppDir); + + await preserveRemoteEnvAroundUpload(conn, remoteAppDir, env, async () => { + await uploadArtifactDirectory(conn, artifactDir, remoteAppDir); + }); + + printSuccess(`Agent 产物已上传到 ${remoteAppDir}`); +} diff --git a/deploy/src/deploy/index.ts b/deploy/src/deploy/index.ts index a880db52..3b1900b5 100644 --- a/deploy/src/deploy/index.ts +++ b/deploy/src/deploy/index.ts @@ -17,6 +17,7 @@ import type { Environment, Service, ServiceEnvConfig } from '../types.js'; import * as frontendDeploy from './frontend.js'; import * as backendDeploy from './backend.js'; import * as licenseDeploy from './license.js'; +import * as agentDeploy from './agent.js'; const deployers: Record Promise; @@ -25,6 +26,7 @@ const deployers: Record { diff --git a/deploy/src/docker.ts b/deploy/src/docker.ts index d6bf8efc..8b5c4077 100644 --- a/deploy/src/docker.ts +++ b/deploy/src/docker.ts @@ -3,10 +3,12 @@ import { join } from 'path'; import { Client } from 'ssh2'; import { + getAgentDeployDir, getBackendDeployDir, getDockerResourceNames, getLicenseDeployDir, getRemoteServiceDir, + resolveAgentPort, resolveBackendPort, resolveEnvDeployDir, resolveSpringProfile, @@ -29,6 +31,10 @@ function resolveBridgePorts(service: Service, cfg: ServiceEnvConfig, env: Enviro const port = resolveBackendPort(env); return { hostPort: port, containerPort: port }; } + if (service === 'agent') { + const port = resolveAgentPort(env); + return { hostPort: port, containerPort: port }; + } return { hostPort: cfg.port, containerPort: cfg.port }; } @@ -61,6 +67,12 @@ export function generateComposeFile(service: Service, cfg: ServiceEnvConfig, env ` - PORT=${containerPort}`, cfg.licenseDbUrl ? ` - DB_URL=${cfg.licenseDbUrl}` : '', ].filter(Boolean).join('\n'); + } else if (service === 'agent') { + // AGENT_ENV 决定加载 .env.{env};PORT 与桥接端口对齐 + envBlock = [ + ` - PORT=${containerPort}`, + ` - AGENT_ENV=${env}`, + ].join('\n'); } const volumeBlock = service === 'backend' @@ -95,13 +107,16 @@ networks: /** 读取运行时 Dockerfile 内容 */ function readRuntimeDockerfile(service: Service): string { - const dockerfileSrc = service === 'backend' - ? join(getBackendDeployDir(), 'Dockerfile') - : join(getLicenseDeployDir(), 'Dockerfile'); - return readFileSync(dockerfileSrc, 'utf8'); + if (service === 'backend') { + return readFileSync(join(getBackendDeployDir(), 'Dockerfile'), 'utf8'); + } + if (service === 'agent') { + return readFileSync(join(getAgentDeployDir(), 'Dockerfile'), 'utf8'); + } + return readFileSync(join(getLicenseDeployDir(), 'Dockerfile'), 'utf8'); } -/** 上传运行时 Dockerfile 到远程环境目录 */ +/** 上传运行时 Dockerfile 到远程环境目录(Agent 另需 entrypoint.sh) */ export async function uploadRuntimeDockerfile( conn: Client, service: Service, @@ -113,6 +128,13 @@ export async function uploadRuntimeDockerfile( const tmp = getLocalTempPath(`ecom-${service}-Dockerfile`); writeFileSync(tmp, readRuntimeDockerfile(service), 'utf8'); await uploadFile(conn, tmp, `${serviceDir}/Dockerfile`); + + if (service === 'agent') { + const entrySrc = join(getAgentDeployDir(), 'entrypoint.sh'); + const tmpEntry = getLocalTempPath('ecom-agent-entrypoint.sh'); + writeFileSync(tmpEntry, readFileSync(entrySrc, 'utf8'), 'utf8'); + await uploadFile(conn, tmpEntry, `${serviceDir}/entrypoint.sh`); + } } /** 检查远程运行时镜像是否已存在 */ diff --git a/deploy/src/index.ts b/deploy/src/index.ts index 05fdc564..350e08e9 100644 --- a/deploy/src/index.ts +++ b/deploy/src/index.ts @@ -27,7 +27,7 @@ import { printBanner, printBox, printError, printInfo, printSuccess } from './ui import { ENV_LABELS, SERVICE_LABELS } from './types.js'; import type { DeployConfig, Environment, Service } from './types.js'; -const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license']; +const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license', 'agent']; async function pause() { await input({ message: '按 Enter 返回主菜单' }); @@ -59,6 +59,7 @@ async function selectService(): Promise { { name: '前端', value: 'frontend' as Service }, { name: '后端', value: 'backend' as Service }, { name: '许可证', value: 'license' as Service }, + { name: '智能体', value: 'agent' as Service }, ], }); } @@ -68,7 +69,7 @@ async function selectServicesMulti(): Promise { const scope = await selectNav({ message: '部署范围', choices: [ - { name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证' }, + { name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证 + 智能体' }, { name: '指定服务…', value: 'pick' as const, description: '空格多选' }, ], }); @@ -81,6 +82,7 @@ async function selectServicesMulti(): Promise { { name: '前端', value: 'frontend' as Service }, { name: '后端', value: 'backend' as Service }, { name: '许可证', value: 'license' as Service }, + { name: '智能体', value: 'agent' as Service }, ], required: true, }); diff --git a/deploy/src/types.ts b/deploy/src/types.ts index b93efe23..68f353f8 100644 --- a/deploy/src/types.ts +++ b/deploy/src/types.ts @@ -1,5 +1,5 @@ export type Environment = 'test' | 'pre' | 'prod'; -export type Service = 'frontend' | 'backend' | 'license'; +export type Service = 'frontend' | 'backend' | 'license' | 'agent'; export interface ServerConfig { host: string; @@ -35,6 +35,7 @@ export const SERVICE_LABELS: Record = { frontend: '前端', backend: '后端', license: '许可证', + agent: '智能体', }; export const ENV_LABELS: Record = {