JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
支持数据库分实例隔离数据
chen huic7f2ee7d931b
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.exampleindex 79e1c1354e..b648196ae4 100644--- a/deploy/enterprise/.env.example+++ b/deploy/enterprise/.env.example@@ -24,8 +24,8 @@ IS_MOUNT_WEB_CODE="false"# 注意 Manager Web 源代码代码需要npm intall之后,才能mount进容器,此操作只需要一次IS_MOUNT_MANAGER_WEB_CODE="false"-# 数据库类型,支持mysql、sqlite、postgresql, 不配默认就是sqlite-DB_TYPE="sqlite"+# 数据库类型,支持 mysql、postgresql,不配默认 mysql+DB_TYPE="mysql"# 部署工具运行所在K8s节点名称# 脚本将尝试自动识别节点名,若识别失败,请手动填写值,取值参考 kubectl get nodes 输出第一列节点名称@@ -69,24 +69,31 @@ CLAW_PVC="jiuwenclaw-pvc"NFS_SC_NAME=""-# ====================== 数据库服务配置 ======================--# 仅当 DB_TYPE 配置为 postgresql / mysql 时,以下配置才会被读取使用+# ====================== 数据库服务配置(仅支持 postgresql / mysql) ======================DB_HOST="" # 外部数据服务的连接地址, 不设置则使用本工具内置部署的数据库服务DB_PORT="" # 数据服务的连接端口(本工具内置部署的数据库服务时设置端口,外部数据库服务填写对应端口)-MANAGER_DB_NAME="" # Manager 业务模块对应的数据库实例名称,未设置则使用默认值"manager"-GATEWAY_DB_NAME="" # Gateway 网关服务对应的数据库实例名称,未设置则使用默认值"gateway"-IDENTITY_DB_NAME="" # Identity 服务对应的数据库实例名称,未设置则使用默认值"identity"-WEB_DB_NAME="" # 企业 Web 会话历史库名称,未设置则使用默认值"web"-AGENT_RUNTIME_DB_NAME="" # Agent Runtime 服务对应的数据库实例名称,未设置则使用默认值"runtime"---# 仅 DB_TYPE 取值为 postgresql / mysql 且使用外部独立数据库服务时,本段账号配置生效,账号权限区分规则:-# 1. 分库独立账号配置:分别定义 MANAGER_DB_USER / MANAGER_DB_PASSWORD、GATEWAY_DB_USER / GATEWAY_DB_PASSWORD、WEB_DB_USER / WEB_DB_PASSWORD、RUNTIME_DB_USER / RUNTIME_DB_PASSWORD-# 2. 全局统一账号配置:仅配置 DB_USER、DB_PASSWORD,Manager、Gateway、Web、Agent Runtime 共用同一套数据库访问凭证-# 地址/端口使用上面的 DB_HOST / DB_PORT-# 未单独配时,部署脚本回退到全局 DB_USER / DB_PASSWORD(与 Manager/Gateway 相同规则)-# 优先级规则:分库专属账号变量优先级 > 全局通用账号变量;若两类变量同时配置,以分库专属账号为准,全局账号配置自动失效++# 当 DB_TYPE 配置为 mysql 时,未设置的时候,默认值为 <module>_<namespace>,以此实现多实例隔离+# 当 DB_TYPE 配置为 postgresql 时,未设置的时候,默认值为 <module>+# 设置时,则优先使用用户配置,覆盖默认规则+MANAGER_DB_NAME="" # Manager管理业务模块数据库名+GATEWAY_DB_NAME="" # Gateway网关服务数据库名+IDENTITY_DB_NAME="" # Identity账号身份服务数据库名+WEB_DB_NAME="" # 企业Web会话、历史存储数据库名+RUNTIME_DB_NAME="" # Agent Runtime运行时服务数据库名++# 仅当 DB_TYPE 配置为 postgresql,如下配置才生效+# 未设置时,默认值为<namespace>,以此实现多实例隔离+# 设置时,则优先使用用户配置,覆盖默认规则+GATEWAY_PG_SCHEMA="" # Gateway网关模块使用的PG schema+MANAGER_PG_SCHEMA="" # Manager管理模块使用的PG schema+IDENTITY_PG_SCHEMA="" # Identity身份模块使用的PG schema+WEB_PG_SCHEMA="" # Web会话模块使用的PG schema+RUNTIME_PG_SCHEMA="" # Agent Runtime运行时模块使用的PG schema++# 支持分库独立账号配置:分别定义 <<MODULE>>_DB_USER / <<MODULE>>_DB_PASSWORD+# 支持全局统一账号配置: 统一定义 DB_USER / DB_PASSWORD+# 优先级规则:若两类变量同时配置,以分库专属账号为准,全局统一账号自动失效DB_USER=""DB_PASSWORD=""GATEWAY_DB_USER=""@@ -170,6 +177,16 @@ MANAGER_PG_SCHEMA=""# Gateway 模块 PostgreSQL 专属 Schema 名称,参数为空则默认使用库内置 public SchemaGATEWAY_PG_SCHEMA=""+# Identity 模块 PostgreSQL 专属 Schema 名称,参数为空则默认使用库内置 public Schema+IDENTITY_PG_SCHEMA=""++# Web 模块 PostgreSQL 专属 Schema 名称,参数为空则默认使用库内置 public Schema+WEB_PG_SCHEMA=""++# Agent Runtime 模块 PostgreSQL 专属 Schema 名称,参数为空则默认使用库内置 public Schema+RUNTIME_PG_SCHEMA=""+# 多实例隔离:非 default 命名空间下,未在此显式设置的 PG_SCHEMA 会自动取 <namespace> 做按 schema 隔离。+# ====================== RabbitMQ 服务配置 ======================# 外部 RabbitMQ 服务的连接地址(格式:host:port), 不设置则使用部署脚本创建的自建 RabbitMQ@@ -191,8 +208,6 @@ RABBITMQ_MGR_NODE_PORT=# ====================== Redis 服务配置 ======================-# DEPLOYMENT_MODE=active-standby 时,Gateway 需要连接 Redis-# Redis 部署形态: standalone(单机/主从) | cluster(三主三从 Cluster)REDIS_MODE="standalone"@@ -292,9 +307,6 @@ GATEWAY_SESSION_MAP_SCOPE="per_chat_bot_user"# 实例标识,留空则Manager在注册时分配,若需复用已有或固定实例标识,请在.env.custom中配置JIUWENCLAW_ID=""-# Gateway 部署模式:standalone(默认,不连 Redis)| active-standby(双实例主备,需 Redis)-DEPLOYMENT_MODE=standalone-# Gateway 服务的容器最小保证 CPU:0.5核(500毫核),K8s 必须分配足够CPU才能调度启动GATEWAY_CPU_REQUEST=500mdiff --git a/deploy/enterprise/README.md b/deploy/enterprise/README.mdindex a7060cd820..bf93519c6e 100644--- a/deploy/enterprise/README.md+++ b/deploy/enterprise/README.md@@ -172,7 +172,6 @@ FEISHU_BOTS="- **nfs**:NFS 存储服务模块- **nfs-sc**:NFS 存储供给模块- **mysql**:MySQL 存储服务模块-- **redis**:Redis 服务模块- **postgresql**:PostgreSQL 存储服务模块- **minio**:Minio 存储服务模块- **log**:日志管理模块@@ -186,7 +185,6 @@ FEISHU_BOTS="./deploy.sh [操作命令] nfs # 仅操作 NFS 存储模块./deploy.sh [操作命令] nfs-sc # 仅操作 NFS 存储供给模块./deploy.sh [操作命令] mysql # 仅操作 MySQL 模块-./deploy.sh [操作命令] redis # 仅操作 Redis 模块./deploy.sh [操作命令] postgresql # 仅操作 PostgreSQL 模块./deploy.sh [操作命令] minio # 仅操作 MinIO 模块./deploy.sh [操作命令] log # 仅操作日志管理模块@@ -198,7 +196,8 @@ FEISHU_BOTS="**重要约束:**-- **NFS / MySQL / PostgreSQL / Redis / Log / Jina:** 以上基础依赖模块全局仅支持单次部署,固定运行于 default 命名空间,部署命令自动忽略自定义命名空间参数。+- **NFS / MySQL / PostgreSQL / Log / Jina:** 以上基础依赖模块全局仅支持单次部署,固定运行于 default 命名空间,部署命令自动忽略自定义命名空间参数。+- **Redis:** 不作为独立模块部署,仅作为 Gateway、Runtime 的附属依赖。每个命名空间拥有独立的 Redis 实例(Deployment 名为 `jiuwenclaw-redis`),实现多业务实例间数据隔离。启动 Gateway 或 Runtime 等依赖 Redis 的业务模块时,部署工具会自动执行就绪检查:已配置外挂 Redis 则复用外部服务;否则复用同命名空间已有的内置 Redis;若同命名空间既无外挂 Redis 也无内置 Redis,则自动拉起一个内置 Redis 实例。- **Web / Gateway / Manager:** 业务服务模块需保持命名空间一致(为了环境隔离与日志运维,禁止使用default命令空间),否则服务间网络互通异常、功能不可用。**使用示例:**@@ -209,7 +208,6 @@ FEISHU_BOTS="./deploy.sh up mysql # 启动 MySQL 存储模块(只需一次)./deploy.sh up postgresql # 启动 PostgreSQL 存储模块(只需一次)./deploy.sh up minio # 启动 MinIO 存储模块(只需一次)-./deploy.sh up redis # 启动 Redis 存储模块(只需一次)./deploy.sh up log # 启动日志管理服务模块(只需一次)./deploy.sh up jina # 启动网页内容提取服务模块(只需一次)./deploy.sh up gateway # 启动 Gateway 服务模块@@ -222,7 +220,6 @@ FEISHU_BOTS="./deploy.sh down gateway # 卸载 Gateway 服务模块(按需卸载)./deploy.sh down jina # 卸载网页内容提取服务模块(非必要不卸载)./deploy.sh down log # 卸载日志管理服务模块(非必要不卸载)-./deploy.sh down redis # 卸载 Redis 存储模块(非必要不卸载)./deploy.sh down minio # 卸载 MinIO 存储模块(非必要不卸载./deploy.sh down postgresql # 卸载 PostgreSQL 存储模块(非必要不卸载)./deploy.sh down mysql # 卸载 MySQL 存储模块(非必要不卸载)@@ -234,7 +231,6 @@ FEISHU_BOTS="./deploy.sh restart mysql # 重启 MySQL 存储模块(非必要不重启)./deploy.sh restart postgresql # 重启 PostgreSQL 存储模块(非必要不重启)./deploy.sh restart minio # 重启 MinIO 存储模块(非必要不重启)-./deploy.sh restart redis # 重启 Redis 存储模块(非必要不重启)./deploy.sh restart log # 重启日志管理模块(非必要不重启)./deploy.sh restart jina # 重启网页内容提取服务模块(非必要不重启)./deploy.sh restart gateway # 重启 Gateway 服务模块(按需重启)@@ -243,12 +239,12 @@ FEISHU_BOTS="```**重要说明:**-每当升级新版本服务时,对于**NFS、NFS-SC、MySQL、PostgreSQL、Redis、MinIO、Log、Jina** 等全局基础依赖组件应尽量保持不变,无需重复部署。仅需对业务服务**Gateway、Web、CLAW-Manager**进行版本替换:在旧版本部署目录中,依次卸载 业务模块;随后切换至新版本部署工具目录,启动对应新版业务模块。+每当升级新版本服务时,对于**NFS、NFS-SC、MySQL、PostgreSQL、MinIO、Log、Jina** 等全局基础依赖组件应尽量保持不变,无需重复部署。**Redis** 已改为按命名空间独立部署、随业务实例隔离(不支持单独部署),升级业务模块时各命名空间下的 Redis 实例保持不变即可。仅需对业务服务**Gateway、Web、CLAW-Manager**进行版本替换:在旧版本部署目录中,依次卸载 业务模块;随后切换至新版本部署工具目录,启动对应新版业务模块。### 2.3 配置参数(选填)**参数说明:**-- `-n`: 指定部署目标命名空间, 从而实现模块多实例隔离部署,不同命名空间的资源不冲突,默认值:`default`。需要注意的是:操作基础依赖模块时,该参数强制失效,固定部署于 `default` 命名空间。+- `-n`: 指定部署目标命名空间, 从而实现模块多实例隔离部署,不同命名空间的资源不冲突,默认值:`default`。需要注意的是:操作 NFS / MySQL / PostgreSQL / Log / Jina 等基础依赖模块时,该参数强制失效,固定部署于 `default` 命名空间;**Redis** 随业务模块按 `-n` 指定的命名空间自动部署(不支持单独部署)。- `--render-only`:只渲染模板输出文件至 conf 目录,不操作集群、不校验集群资源**参数使用示例:**@@ -331,13 +327,13 @@ NFS_SC_NAME=""### 3.2 部署数据库服务-本产品支持 SQLite、PostgreSQL、MySQL 三种数据库类型,可根据具体需求三选一配置即可。选定数据库类型后,在配置文件 `.env.custom` 中指定:+本产品支持 PostgreSQL、MySQL 两种数据库类型,可根据具体需求二选一配置即可。选定数据库类型后,在配置文件 `.env.custom` 中指定:```-# 数据库类型,支持mysql、sqlite、postgresql, 默认为sqlite-DB_TYPE="sqlite"+# 数据库类型,支持 mysql、postgresql,默认 mysql+DB_TYPE="mysql"```-**说明:** SQLite 为嵌入式内置数据库,无需部署。+**说明:** SQLite 已不再支持(企业版多 Pod 共享场景下本地 sqlite 文件无法跨 Pod 共享);个人版单机走内存/本地,不经此部署工具。#### 3.2.1 工具内置部署(开发环境可用)@@ -384,29 +380,44 @@ GATEWAY_DB_PASSWORD=""MANAGER_DB_USER=""MANAGER_DB_PASSWORD=""-# (仅 PostgreSQL 有效) Manager 模块的专属 Schema 名称, 默认为public+# (仅 PostgreSQL 有效) 各模块的专属 Schema 名称, 默认为 publicMANAGER_PG_SCHEMA=""--# (仅 PostgreSQL 有效) Gateway 模块的专属 Schema 名称, 默认为publicGATEWAY_PG_SCHEMA=""+IDENTITY_PG_SCHEMA=""+WEB_PG_SCHEMA=""+RUNTIME_PG_SCHEMA=""```+#### 3.2.3 多实例数据库隔离++数据库服务(MySQL/PostgreSQL)为所有业务实例共享同一台 DB Server。在多实例(多命名空间)部署场景下,部署工具会自动为每个实例隔离各模块数据,实例间互不干扰,默认无需任何手动配置。++**默认行为(推荐)**:未显式指定各模块数据库名时,部署工具按实例(命名空间)自动为每个模块分配独立的数据库,天然保证各实例数据隔离:++- **MySQL**:每个实例的每个模块使用形如 `<模块库名>_<命名空间>` 的独立数据库(如实例 `test` 的 Gateway 库为 `gateway_test`)。+- **PostgreSQL**:在同一共享数据库内,为每个实例使用以命名空间命名的独立 schema 实现隔离(如实例 `test` 使用 schema `test`)。++各模块默认库名为:Gateway→`gateway`、Manager→`manager`、Identity→`identity`、Runtime→`runtime`、Web→`web`。++**自定义数据库名**:如需指定,可在 `.env.custom` 中为各模块设置对应变量(MySQL 为 `*_DB_NAME`,PostgreSQL 为 `*_PG_SCHEMA`)。一旦显式设置,部署工具将直接采用该值并不再自动分配——**请务必保证同一套部署中每个实例的各模块数据库名(或 PostgreSQL schema 名)互不相同**,否则不同实例会读写同一数据库,导致数据串台。++> 提示:如无特殊需求,建议保持默认,由部署工具自动分配,既省心又能可靠保证隔离性。+### 3.3 部署redis服务-当Gateway开启主备模式时,需要提前部署Redis服务。+Redis 不支持单独部署,仅作为 Gateway、Runtime 的附属依赖,随业务模块启动时按命名空间自动就绪。每个命名空间拥有独立的 Redis 实例(Deployment 名为 `jiuwenclaw-redis`),实现多业务实例间的数据隔离。-#### 3.3.1 工具内置部署(开发环境可用)+部署 Gateway 或 Runtime 等依赖 Redis 的业务模块时,部署工具会自动执行 Redis 就绪检查(`ensure_redis_up`),其行为如下:-本部署工具提供一键部署能力,可在集群内快速拉起单节点 Redis 实例:-```-./deploy.sh up redis # 部署 Redis(只需也只能部署一次)-```+1. 若已在 `.env.custom` 中配置外挂 Redis(`REDIS_HOST`),则直接复用外部 Redis 服务,跳过内置部署;+2. 否则检测同命名空间下是否已存在内置 Redis 实例(Deployment `jiuwenclaw-redis`),存在则直接复用;+3. 若同命名空间下既未配置外挂 Redis、也不存在内置 Redis 实例,则自动拉起一个单节点内置 Redis 实例于该命名空间。-**注意:** 本部署工具仅支持单实例Redis服务部署,如需高可用Redis服务,请采用外部独立部署方式。+**注意:** 内置 Redis 为单节点实例,如需高可用 Redis 服务,请采用外部独立部署方式。-#### 3.3.2 外部独立部署(生产环境推荐)+#### 3.3.1 外部独立部署(生产环境推荐)-生产环境下,推荐用户自行搭建高可用的外部 Redis 服务,搭建完成后需在自定义配置文件 `.env.custom` 中填写如下参数,完成外部 Redis 服务的对接工作。+生产环境下,推荐用户自行为每套实例搭建高可用的外部 Redis 服务,搭建完成后需在自定义配置文件 `.env.custom` 中填写如下参数,完成外部 Redis 服务的对接工作。```# 外部 Redis 服务的连接地址@@ -580,7 +591,7 @@ LOG_TO_FILE_ENABLED=falseJiuwenSwarm 企业级服务完整支持基于 Kubernetes 命名空间的多实例隔离部署,可在同一集群内通过不同命名空间部署多套独立运行的业务实例,实现环境隔离、多实例并行使用。-同一业务实例下的所有组件(Gateway、Web、CLAW-Manager)只有部署在同一个命名空间内才能服务调用和互通。而基础依赖组件(NFS、MySQL、Redis、MinIO、PostgreSQL)为所有业务实例的公共组件,无需随业务实例重复部署。+同一业务实例下的所有组件(Gateway、Web、CLAW-Manager、Redis)只有部署在同一个命名空间内才能服务调用和互通。其中 NFS、MySQL、MinIO、PostgreSQL 等基础依赖组件为所有业务实例的公共组件,固定部署于 default 命名空间,无需随业务实例重复部署;而 Redis 不作为独立模块部署,随业务实例按命名空间隔离,启动业务模块时由部署工具自动就绪。**注意**:- 业务组件请勿部署至 default 默认命名空间。@@ -600,11 +611,11 @@ Gateway 是 JiuwenSwarm 的多渠道接入网关与消息调度核心,负责 A部署时会检查 `.env.custom` 中的 `JIUWENCLAW_ID`:未配置则自动生成并写回;已配置则沿用原值。-注意:默认以单机单实例模式运行;若需启用双实例主备高可用架构,请在启动前,修改配置文件 `.env.custom` 如下参数:+注意:Gateway 仅支持分布式多副本部署模式(`DEPLOYMENT_MODE=distributed`):多副本同时在线、连接 Redis 共享会话、无选主(cron 默认关闭、仅 web/tui 通道)。所需 Redis 由部署工具按命名空间自动拉起(详见 3.3 节)。启动前可在配置文件 `.env.custom` 中确认如下参数:```-# Gateway 部署模式:standalone(默认,不连 Redis)| active-standby(双实例主备,需 Redis)-DEPLOYMENT_MODE=standalone+# Gateway 部署模式:distributed(多副本同时在线,连接 Redis 共享 session,无选主;cron 默认关闭;仅 web/tui 通道)+DEPLOYMENT_MODE=distributed```若需为业务服务挂载外部 NFS 服务实现数据持久化,需在配置文件`.env.custom` 中设置:diff --git a/deploy/enterprise/args_handler.sh b/deploy/enterprise/args_handler.shindex 55c8c8c778..02d3602758 100755--- a/deploy/enterprise/args_handler.sh+++ b/deploy/enterprise/args_handler.sh@@ -12,7 +12,7 @@ parse_args() {CMD="${args[$i]}"i=$((i+1));;- nfs|nfs-sc|rabbitmq|mysql|redis|postgresql|minio|log|jina|gateway|web|manager|runtime)+ nfs|nfs-sc|rabbitmq|mysql|postgresql|minio|log|jina|gateway|web|manager|runtime)MODULES+=("${args[$i]^^}")i=$((i+1));;@@ -68,7 +68,6 @@ Modules (Optional):nfs NFS service module (deploys to default namespace, ignores -n parameter)rabbitmq RabbitMQ module (deploys to default namespace, ignores -n parameter)mysql MySQL module (deploys to default namespace, ignores -n parameter)- redis Redis module (deploys to default namespace, ignores -n parameter)minio Minio module (deploys to default namespace, ignores -n parameter)log Log module (deploys to default namespace, ignores -n parameter)jina Jina module (deploys to default namespace, ignores -n parameter)diff --git a/deploy/enterprise/check_handler.sh b/deploy/enterprise/check_handler.shindex 73f4e90e74..01b6dfb971 100755--- a/deploy/enterprise/check_handler.sh+++ b/deploy/enterprise/check_handler.sh@@ -145,6 +145,55 @@ check_if_nfs_sc_up() {DEPLOY_VARS["CLAW_PVC"]="jiuwenclaw-pvc"}+# 变量规则一:+# mysql: DB_NAME 拼为 <<MODULE>>_<<NAMESPACE>>(按 db 隔离各实例)+# postgresql: PG_SCHEMA 取 NAMESPACE(按 schema 隔离各实例)+# 变量规则二:+# 支持分库独立账号配置:分别定义 <<MODULE>>_DB_USER / <<MODULE>>_DB_PASSWORD+# 支持全局统一账号配置: 统一定义 DB_USER / DB_PASSWORD+# 优先级规则:若两类变量同时配置,以分库专属账号为准,全局统一账号自动失效+set_db_var() {+ local module=$1+ local db_type=$2+ local name=$3+ local namespace="${DEPLOY_VARS["NAMESPACE"]}"+ local lmodule="${module,,}"+ local full_name="${module}_${name}"++ case "$name" in+ DB_NAME)+ if [[ -z "${DEPLOY_VARS["${full_name}"]:-}" ]]; then+ if [ "${db_type}" == "mysql" ]; then+ DEPLOY_VARS["${full_name}"]="${lmodule}_${namespace}"+ else+ DEPLOY_VARS["${full_name}"]="${lmodule}"+ fi+ fi+ return+ ;;+ PG_SCHEMA)+ if [[ -z "${DEPLOY_VARS["${full_name}"]:-}" ]]; then+ if [ ${db_type} == "postgresql" ]; then+ DEPLOY_VARS["${full_name}"]="${namespace}"+ fi+ fi+ return+ ;;+ DB_USER|DB_PASSWORD)+ if [ -z "${DEPLOY_VARS["${full_name}"]:-}" ]; then+ DEPLOY_VARS["${full_name}"]=${DEPLOY_VARS["${name}"]:-}+ fi+ ;;+ *)+ error "invaild var name"+ ;;+ esac++ if [ -z "${DEPLOY_VARS["${full_name}"]:-}" ]; then+ error "Please set up ${full_name} or ${name}."+ fi+}+check_if_db_up() {# 已经执行过检查,直接返回,避免重复校验if [[ "${DEPLOY_VARS["DB_CHECKED"]:-}" == "true" ]]; then@@ -152,15 +201,15 @@ check_if_db_up() {filocal db_type="${DEPLOY_VARS["DB_TYPE"]}"- local db_type_upper="${db_type^^}"- local name="${DEPLOY_VARS["${db_type_upper}_NAME"]}"-info "DB_TYPE: ${db_type}"DEPLOY_VARS["DB_CHECKED"]="true"- if [ "${db_type}" == "sqlite" ]; then- return+ if [ "${db_type}" != "mysql" ] && [ "${db_type}" != "postgresql" ]; then+ error "DB_TYPE='${db_type}' is not supported in enterprise deploy; use 'mysql' or 'postgresql'"fi+ local db_type_upper="${db_type^^}"+ local name="${DEPLOY_VARS["${db_type_upper}_NAME"]}"+# Build-In DB serverif [[ -z "${DEPLOY_VARS["DB_HOST"]:-}" || "${DEPLOY_VARS["DB_HOST"]}" == "${name}-headless.default" ]]; thenif ! check_k8s_resource_exists "statefulset" "${name}"; then@@ -176,6 +225,9 @@ check_if_db_up() {doDEPLOY_VARS["${module}_DB_USER"]="root"DEPLOY_VARS["${module}_DB_PASSWORD"]=${DEPLOY_VARS["MYSQL_ROOT_PASSWORD"]}+ for name in DB_NAME PG_SCHEMA; do+ set_db_var "${module}" "${db_type}" "${name}"+ donedone;;postgresql)@@ -185,6 +237,9 @@ check_if_db_up() {doDEPLOY_VARS["${module}_DB_USER"]="postgres"DEPLOY_VARS["${module}_DB_PASSWORD"]=${DEPLOY_VARS["POSTGRESQL_PASSWORD"]}+ for name in DB_NAME PG_SCHEMA; do+ set_db_var "${module}" "${db_type}" "${name}"+ donedone;;*)@@ -194,29 +249,16 @@ check_if_db_up() {returnfi- info "Use external ${DB_TYPE} server"+ info "Use external ${db_type} server"if [ -z "${DEPLOY_VARS["DB_PORT"]:-}" ]; thenerror "Please define DB_PORT in .env.custom"fi- for module in GATEWAY WEB MANAGER IDENTITY RUNTIME- do- if [ -z "${DEPLOY_VARS["${module}_DB_USER"]:-}" ]; then- DEPLOY_VARS["${module}_DB_USER"]=${DEPLOY_VARS["DB_USER"]}- fi-- if [ -z "${DEPLOY_VARS["${module}_DB_USER"]:-}" ]; then- error "Please set up ${module}_DB_USER or DB_USER."- fi-- if [ -z "${DEPLOY_VARS["${module}_DB_PASSWORD"]:-}" ]; then- DEPLOY_VARS["${module}_DB_PASSWORD"]=${DEPLOY_VARS["DB_PASSWORD"]}- fi-- if [ -z "${DEPLOY_VARS["${module}_DB_PASSWORD"]:-}" ]; then- error "Please set up ${module}_DB_PASSWORD or DB_PASSWORD."- fi+ for module in GATEWAY WEB MANAGER IDENTITY RUNTIME; do+ for name in DB_USER DB_PASSWORD DB_NAME PG_SCHEMA; do+ set_db_var "${module}" "${db_type}" "${name}"+ donedone}@@ -238,30 +280,45 @@ check_if_obs_up() {info "Use built-in Minio server"}-check_if_redis_up() {+ensure_redis_up() {# 已经执行过检查,直接返回,避免重复校验if [[ "${DEPLOY_VARS["REDIS_CHECKED"]:-}" == "true" ]]; thenreturnfi- local mode="${DEPLOY_VARS["DEPLOYMENT_MODE"]}"- local name="${DEPLOY_VARS["REDIS_NAME"]}"-DEPLOY_VARS["REDIS_CHECKED"]="true"++ local namespace="${DEPLOY_VARS["NAMESPACE"]}"+ local redis_name="${DEPLOY_VARS["REDIS_NAME"]}"++ # 已设外挂 Redis,跳过if [ -n "${DEPLOY_VARS["REDIS_HOST"]:-}" ]; then- info "Use external Redis server"+ info "Use external Redis server: ${DEPLOY_VARS["REDIS_HOST"]}"DEPLOY_VARS["ENABLE_EXTERNAL_REDIS"]="true"returnfi- # No Build-In Redis server- if ! check_k8s_resource_exists "deployment" "${name}"; then- error "Redis is not deployed. Please deploy it first with: ./$(basename "$0") up redis"+ DEPLOY_VARS["REDIS_HOST"]="${redis_name}.${namespace}"+ DEPLOY_VARS["REDIS_PORT"]="6379"++ # 同命名空间已有 redis,直接用+ if check_k8s_resource_exists "deployment" "${redis_name}" "${namespace}"; then+ info "Use built-in Redis server in namespace: ${namespace}"+ returnfi- info "Use built-in Redis server"- DEPLOY_VARS["REDIS_HOST"]="${name}.default"- DEPLOY_VARS["REDIS_PORT"]="6379"+ render_redis_files++ # 渲染模式不实际部署+ if [ "${DEPLOY_VARS["RENDER_ONLY"]}" == "true" ]; then+ info "rendering Redis files for namespace: ${namespace}"+ return+ fi++ # 同命名空间没有 redis 且非外挂 → 自动启动一个+ info "Redis not found in namespace '${namespace}', auto-deploying built-in Redis..."+ deploy_redis+ success "Deploy Redis in namespace '${namespace}'"}check_if_jina_up() {@@ -377,10 +434,6 @@ check_minio_up_dependency(){fi}-check_redis_up_dependency() {- info "Redis module has no dependencies"-}-check_rabbitmq_up_dependency(){local rabbit_path="${DEPLOY_VARS["NFS_POD_PATH"]}/${DEPLOY_VARS["RABBITMQ_NAME"]}"local nfs_dname=${DEPLOY_VARS["NFS_NAME"]}@@ -438,8 +491,9 @@ check_gateway_up_dependency(){ficheck_if_db_up- check_if_redis_upcheck_if_jina_up++ ensure_redis_up}check_web_up_dependency(){@@ -474,5 +528,5 @@ check_manager_up_dependency(){check_runtime_up_dependency(){check_if_db_up- check_if_redis_up+ ensure_redis_up}diff --git a/deploy/enterprise/example/gateway-env.configmap.yaml b/deploy/enterprise/example/gateway-env.configmap.yamlindex 050c993190..eeac6d2e81 100644--- a/deploy/enterprise/example/gateway-env.configmap.yaml+++ b/deploy/enterprise/example/gateway-env.configmap.yaml@@ -26,7 +26,7 @@ data:CLAW_MOUNT_TYPE: nfsCLAW_NFS_PATH: <<NFS_SHARE_PATH>>/jiuwenclawCLAW_NFS_SERVER: <<NFS_SERVER_ADDR>>- DEPLOYMENT_MODE: active-standby+ DEPLOYMENT_MODE: distributedENTERPRISE_WEB_ENABLED: "true"ENTERPRISE_WEB_GATEWAY_URL: ws://jiuwenclaw-web:19000/gatewayEXTENSION_DIRS: /app/jiuwenclaw/packages/jiuwenclaw-ee/gateway/extensionsdiff --git a/deploy/enterprise/gateway_handler.sh b/deploy/enterprise/gateway_handler.shindex f5c5a1fc21..1ea3d16146 100755--- a/deploy/enterprise/gateway_handler.sh+++ b/deploy/enterprise/gateway_handler.sh@@ -6,12 +6,6 @@ gen_gateway_env_file() {local env_template_file="${CONFIG["GATEWAY_ENV_TEMPLATE_FILE"]}"local envfile_name="${DEPLOY_VARS["GATEWAY_ENV_FILE_CM_NAME"]}"local env_file="${CONFIG["GATEWAY_ENV_FILE"]}"- local deploy_mode="${DEPLOY_VARS["DEPLOYMENT_MODE"]}"--- if [ "${deploy_mode}" == "active-standby" ]; then- DEPLOY_VARS["GATEWAY_INSTANCE_ID"]="gateway-${namespace}"- firender_config_template "${env_template_file}" "${env_file}" "DEPLOY_VARS"@@ -125,9 +119,6 @@ render_gateway_files() {ensure_jiuwenclaw_idgen_gateway_env_filegen_gateway_config_file- if [ "${DEPLOY_VARS["DEPLOYMENT_MODE"]}" == "active-standby" ]; then- DEPLOY_VARS["GATEWAY_REPLICAS"]="2"- fiif [[ "${mount_type}" == "pvc" && "${is_external_pvc}" == "false" ]]; thenrender_config_template "${pvc_template_file}" "${pvc_file}" "DEPLOY_VARS"@@ -203,4 +194,5 @@ uninstall_gateway() {exec_cmd kubectl delete -f ${pvc_file} --ignore-not-found=truefiuninstall_secret_configmap+ ensure_redis_down "runtime"}diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.shindex 44b719ad94..19f9047205 100755--- a/deploy/enterprise/global_vars.sh+++ b/deploy/enterprise/global_vars.sh@@ -82,7 +82,7 @@ declare -A ARGS=(# ==== All available modules ====-declare -ga ALL_MODULES=("NFS" "NFS-SC" "RABBITMQ" "MYSQL" "REDIS" "POSTGRESQL" "MINIO" "LOG" "JINA" "GATEWAY" "WEB" "MANAGER" "RUNTIME")+declare -ga ALL_MODULES=("NFS" "NFS-SC" "RABBITMQ" "MYSQL" "POSTGRESQL" "MINIO" "LOG" "JINA" "GATEWAY" "WEB" "MANAGER" "RUNTIME")declare -ga MODULES=()@@ -96,7 +96,6 @@ declare -A DEPLOY_VARS=(["RUNTIME_POD_PKG_PATH"]="/usr/local/lib/python3.11/site-packages/openjiuwen_runtime"["CORE_POD_PKG_PATH"]="/usr/local/lib/python3.11/site-packages/openjiuwen"["JIUWENBOX_POD_PKG_PATH"]="/usr/local/lib/python3.11/site-packages/jiuwenbox"-["AGENT_BOT_ID_GROUP_NUM"]="0"["AGENT_SERVER_HOME"]="/home/app"["AGENT_SERVER_POD_NAME"]="jiuwenclaw-agentserver"@@ -107,8 +106,7 @@ declare -A DEPLOY_VARS=(["CLAW_MOUNT_TYPE"]="pvc"["CLAW_STORAGE_SIZE"]="1Gi"["COLLECT_LOG_MASK_ENABLED"]="false"- ["DB_TYPE"]="sqlite"- ["DEPLOYMENT_MODE"]="standalone"+ ["DB_TYPE"]="mysql"["WEB_PORT"]="19000"["GATEWAY_PORT"]="19001"["GATEWAY_HTTP_PORT"]="19001"@@ -130,8 +128,6 @@ declare -A DEPLOY_VARS=(["GATEWAY_CLAW_WS_PING_TIMEOUT"]="20.0"["TOOL_RESULT_DISPLAY_MAX_CHARS"]="500"["GATEWAY_CONFIG_MAP_NAME"]="jiuwenclaw-gateway-config"- ["GATEWAY_DB_NAME"]="gateway"- ["WEB_DB_NAME"]="web"["GATEWAY_DB_MAX_OVERFLOW"]="20"["GATEWAY_DB_POOL_SIZE"]="2"["GATEWAY_DB_POOL_TIMEOUT"]="30"@@ -141,13 +137,10 @@ declare -A DEPLOY_VARS=(["LOG_MASK_ENABLED"]="true"["LOG_TO_FILE_ENABLED"]="true"["GATEWAY_NAME"]="jiuwenclaw-gateway"- ["GATEWAY_PG_SCHEMA"]="public"["GATEWAY_REPLICAS"]="1"- ["GATEWAY_SQLITE_PATH"]="gateway.db"["IS_UP_MANAGER_WEB"]="true"["IDENTITY_NAME"]="jiuwenclaw-identity"["IDENTITY_REST_PORT"]="8770"- ["IDENTITY_DB_NAME"]="identity"["IDENTITY_SEED_ADMIN"]="true"["IDENTITY_SEED_USER1"]="true"["IDENTITY_FEDERATION_DEMO_ENABLED"]="false"@@ -161,12 +154,9 @@ declare -A DEPLOY_VARS=(["JINA_READER_ENDPOINT"]="https://r.jinaai.cn"["JINA_READER_NUM"]="2"["FLUENT_BIT_IMAGE"]="fluent/fluent-bit:3.0.0"- ["MANAGER_DB_NAME"]="manager"- ["MANAGER_PG_SCHEMA"]="public"["MANAGER_REST_PORT"]="8765"["MANAGER_SERVER_NAME"]="jiuwenclaw-manager-server"["MANAGER_SERVER_REPLICAS"]="1"- ["MANAGER_SQLITE_PATH"]="manager.db"["MANAGER_WEB_NAME"]="jiuwenclaw-manager-web"["MANAGER_WEB_PORT"]="5273"["MANAGER_WS_PORT"]="8766"@@ -212,7 +202,7 @@ declare -A DEPLOY_VARS=(["REDIS_IMAGE"]="redis:7-alpine"["REDIS_KEY_PREFIX"]="jiuwenclaw:"["REDIS_MODE"]="standalone"- ["REDIS_NAME"]="redis"+ ["REDIS_NAME"]="jiuwenclaw-redis"["REDIS_PASSWORD"]=""["REDIS_PORT"]="6379"["REDIS_MODE"]="standalone"@@ -231,7 +221,6 @@ declare -A DEPLOY_VARS=(["AGENT_RUNTIME_PORT"]="8091"["GATEWAY_RUNTIME_MANAGER_URL"]="http://jiuwenclaw-agent-runtime:8091"["AGENT_RUNTIME_SYNC_TIMEOUT"]="10"- ["AGENT_RUNTIME_DB_NAME"]="runtime"["AGENT_RUNTIME_REDIS_DB"]="2"["AGENT_RUNTIME_REQUEST_TIMEOUT"]="300"["AGENT_RUNTIME_SCOPE_FULL_TIMEOUT"]="8"diff --git a/deploy/enterprise/manager_handler.sh b/deploy/enterprise/manager_handler.shindex 647da55478..d62624181f 100755--- a/deploy/enterprise/manager_handler.sh+++ b/deploy/enterprise/manager_handler.sh@@ -33,7 +33,7 @@ gen_identity_file() {select(.kind == "Deployment").spec.template.spec.containers[0].env += [{"name": "IDENTITY_PG_SCHEMA",- "value": "'"${DEPLOY_VARS["MANAGER_PG_SCHEMA"]}"'"+ "value": "'"${DEPLOY_VARS["IDENTITY_PG_SCHEMA"]}"'"}]' -i "${file}"fidiff --git a/deploy/enterprise/redis_handler.sh b/deploy/enterprise/redis_handler.shindex 22e801d71b..4d5e109cbb 100755--- a/deploy/enterprise/redis_handler.sh+++ b/deploy/enterprise/redis_handler.sh@@ -10,17 +10,54 @@ render_redis_files() {}deploy_redis() {+ local namespace="${DEPLOY_VARS["NAMESPACE"]}"local redis_name="${DEPLOY_VARS["REDIS_NAME"]}"local file="${CONFIG["REDIS_FILE"]}"exec_cmd kubectl apply -f "${file}"- wait_k8s_resource_ready "deployment" "${redis_name}" "default"+ wait_k8s_resource_ready "deployment" "${redis_name}" "${namespace}"}uninstall_redis() {+ local namespace="${DEPLOY_VARS["NAMESPACE"]}"local redis_name="${DEPLOY_VARS["REDIS_NAME"]}"local file="${CONFIG["REDIS_FILE"]}"exec_cmd kubectl delete -f "${file}" --ignore-not-found=true- wait_pod_terminated "${redis_name}" "default"+ wait_pod_terminated "${redis_name}" "${namespace}"+}+++# gateway / runtime 两个模块共用同一份内置 Redis,不能贸然关停。+# 只有两个模块 都关停之后,才能关停+ensure_redis_down() {+ local namespace="${DEPLOY_VARS["NAMESPACE"]}"+ local name="${DEPLOY_VARS["REDIS_NAME"]}"++ # 渲染模式不动集群+ if [ "${DEPLOY_VARS["RENDER_ONLY"]}" == "true" ]; then+ return+ fi++ # 外挂 Redis 由用户自行管理,本工具不负责卸载+ if [ "${DEPLOY_VARS["ENABLE_EXTERNAL_REDIS"]}" == "true" ]; then+ info "External Redis in use, skip shutting down built-in Redis."+ return+ fi++ # 当前命名空间内已无内置 Redis Deployment,说明已卸载或从未部署+ if ! check_k8s_resource_exists "deployment" "${name}" "${namespace}"; then+ info "Built-in Redis '${name}' not found in namespace '${namespace}', nothing to do."+ return+ fi++ for dname in ${DEPLOY_VARS["GATEWAY_NAME"]} ${DEPLOY_VARS["AGENT_RUNTIME_NAME"]}+ do+ if check_k8s_resource_exists "deployment" "${dname}" "${namespace}"; then+ info " ${dname} still running in namespace '${namespace}', keep Redis alive."+ return+ fi+ done+ uninstall_redis+ success "Built-in Redis '${name}' has been shut down."}diff --git a/deploy/enterprise/runtime_handler.sh b/deploy/enterprise/runtime_handler.shindex 89b3d7a9a5..d6dec19251 100755--- a/deploy/enterprise/runtime_handler.sh+++ b/deploy/enterprise/runtime_handler.sh@@ -8,6 +8,16 @@ gen_runtime_file() {render_config_template "${template_file}" "${file}" "DEPLOY_VARS"enable_dev_mode_if_needed ${file} runtime+ if [ "${DEPLOY_VARS["DB_TYPE"]}" == "postgresql" ]; then+ yq eval '+ select(.kind == "Deployment").spec.template.spec.containers[0].env += [+ {+ "name": "OPENJIUWEN_SERVICE_PG_SCHEMA",+ "value": "'"${DEPLOY_VARS["RUNTIME_PG_SCHEMA"]}"'"+ }+ ]' -i "${file}"+ fi+add_resource_if_set "RUNTIME" "${file}"}@@ -52,4 +62,5 @@ uninstall_runtime() {info "Deleting remaining Runtime resources (ServiceAccount, Role, Service, ...)"exec_cmd kubectl delete -f "${file}" --ignore-not-found=trueuninstall_secret_configmap+ ensure_redis_down "gateway"}diff --git a/deploy/enterprise/templates/.env.custom.template b/deploy/enterprise/templates/.env.custom.templateindex 9fc60cc356..be75a370f9 100644--- a/deploy/enterprise/templates/.env.custom.template+++ b/deploy/enterprise/templates/.env.custom.template@@ -68,15 +68,19 @@ DB_PASSWORD="<<DB_PASSWORD>>"# 如果外挂DB是Postgres,可以设置GATEWAY_PG_SCHEMA="<<GATEWAY_PG_SCHEMA>>"MANAGER_PG_SCHEMA="<<MANAGER_PG_SCHEMA>>"+IDENTITY_PG_SCHEMA="<<IDENTITY_PG_SCHEMA>>"+WEB_PG_SCHEMA="<<WEB_PG_SCHEMA>>"+RUNTIME_PG_SCHEMA="<<RUNTIME_PG_SCHEMA>>"+# 非 default 命名空间下:mysql 的 DB_NAME 自动拼为 <dbname>_<namespace>;+# postgresql 的 PG_SCHEMA 自动取 <namespace>。显式设置某模块的 DB_NAME/PG_SCHEMA 后,该模块不再自动拼接。# 外挂NFSCLAW_MOUNT_TYPE="nfs"NFS_SERVER_ADDR="<<NFS_SERVER_ADDR>>"NFS_SHARE_PATH="<<NFS_SHARE_PATH>>"--# Gatway使用主备模式-DEPLOYMENT_MODE=active-standby+# Fateway多副本模式+DEPLOYMENT_MODE=distributed# 外挂RedisREDIS_HOST="<<REDIS_HOST>>"diff --git a/deploy/enterprise/templates/gateway.template.env b/deploy/enterprise/templates/gateway.template.envindex 262dd3135a..e8f245fb4b 100644--- a/deploy/enterprise/templates/gateway.template.env+++ b/deploy/enterprise/templates/gateway.template.env@@ -109,7 +109,6 @@ TOOL_RESULT_DISPLAY_MAX_CHARS=<<TOOL_RESULT_DISPLAY_MAX_CHARS>># Gateway databaseGATEWAY_DB_TYPE=<<DB_TYPE>>-GATEWAY_SQLITE_PATH=<<GATEWAY_SQLITE_PATH>>GATEWAY_DB_HOST=<<DB_HOST>>GATEWAY_DB_PORT=<<DB_PORT>>GATEWAY_DB_USER=<<GATEWAY_DB_USER>>@@ -157,9 +156,9 @@ JIUWENBOX_MEMORY_REQUEST=<<JIUWENBOX_MEMORY_REQUEST>>JIUWENBOX_CPU_LIMIT=<<JIUWENBOX_CPU_LIMIT>>JIUWENBOX_MEMORY_LIMIT=<<JIUWENBOX_MEMORY_LIMIT>>-# Gateway deployment mode (standalone | active-standby)-DEPLOYMENT_MODE=<<DEPLOYMENT_MODE>>-GATEWAY_INSTANCE_ID=<<GATEWAY_INSTANCE_ID>>+# Gateway多副本模式+DEPLOYMENT_MODE=distributed+GATEWAY_INSTANCE_ID=<<GATEWAY_NAME>>-<<NAMESPACE>>REDIS_HOST=<<REDIS_HOST>>REDIS_PORT=<<REDIS_PORT>>REDIS_MODE=<<REDIS_MODE>>diff --git a/deploy/enterprise/templates/manager-server.template.yaml b/deploy/enterprise/templates/manager-server.template.yamlindex 4f5efd289b..228427cdfc 100644--- a/deploy/enterprise/templates/manager-server.template.yaml+++ b/deploy/enterprise/templates/manager-server.template.yaml@@ -69,8 +69,6 @@ spec:value: "<<MANAGER_REST_PORT>>"- name: MANAGER_DB_TYPEvalue: "<<DB_TYPE>>"- - name: MANAGER_SQLITE_PATH- value: "<<MANAGER_SQLITE_PATH>>"- name: MANAGER_DB_HOSTvalue: "<<DB_HOST>>"- name: MANAGER_DB_PORTdiff --git a/deploy/enterprise/templates/redis.template.yaml b/deploy/enterprise/templates/redis.template.yamlindex 05eb36947d..2b6c571955 100644--- a/deploy/enterprise/templates/redis.template.yaml+++ b/deploy/enterprise/templates/redis.template.yaml@@ -3,7 +3,7 @@ apiVersion: v1kind: Servicemetadata:name: <<REDIS_NAME>>- namespace: default+ namespace: <<NAMESPACE>>spec:selector:app: <<REDIS_NAME>>@@ -17,6 +17,7 @@ apiVersion: v1kind: Servicemetadata:name: <<REDIS_NAME>>-nodeport+ namespace: <<NAMESPACE>>spec:type: NodePortports:@@ -31,7 +32,7 @@ apiVersion: apps/v1kind: Deploymentmetadata:name: <<REDIS_NAME>>- namespace: default+ namespace: <<NAMESPACE>>spec:replicas: 1selector:diff --git a/deploy/enterprise/templates/runtime.template.yaml b/deploy/enterprise/templates/runtime.template.yamlindex fb873bde45..cb066187b7 100644--- a/deploy/enterprise/templates/runtime.template.yaml+++ b/deploy/enterprise/templates/runtime.template.yaml@@ -84,14 +84,18 @@ spec:httpGet:path: /healthzport: rest- initialDelaySeconds: 5+ initialDelaySeconds: 10periodSeconds: 5+ timeoutSeconds: 2+ failureThreshold: 3livenessProbe:httpGet:path: /healthzport: rest- initialDelaySeconds: 10+ initialDelaySeconds: 60periodSeconds: 10+ timeoutSeconds: 3+ failureThreshold: 6envFrom:- secretRef:name: <<SECRET_CM_NAME>>@@ -118,7 +122,7 @@ spec:- name: OPENJIUWEN_SERVICE_DB_PORTvalue: "<<DB_PORT>>"- name: OPENJIUWEN_SERVICE_DB_NAME- value: "<<AGENT_RUNTIME_DB_NAME>>"+ value: "<<RUNTIME_DB_NAME>>"- name: OPENJIUWEN_SERVICE_DB_USERvalue: "<<RUNTIME_DB_USER>>"- name: OPENJIUWEN_SERVICE_DEPLOY_REPLICASdiff --git a/deploy/enterprise/tests/test_identity_user_web_deploy.sh b/deploy/enterprise/tests/test_identity_user_web_deploy.shdeleted file mode 100755index fd091667d6..0000000000--- a/deploy/enterprise/tests/test_identity_user_web_deploy.sh+++ /dev/null@@ -1,188 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"--source "${SCRIPT_DIR}/common.sh"-source "${SCRIPT_DIR}/global_vars.sh"-source "${SCRIPT_DIR}/cmd_handler.sh"-source "${SCRIPT_DIR}/envfile_handler.sh"-source "${SCRIPT_DIR}/template_handler.sh"-source "${SCRIPT_DIR}/check_handler.sh"-source "${SCRIPT_DIR}/web_handler.sh"-source "${SCRIPT_DIR}/manager_handler.sh"--TEST_DIR=""--cleanup() {- if [ -n "${TEST_DIR}" ] && [ -d "${TEST_DIR}" ]; then- rm -rf -- "${TEST_DIR}"- fi-}--assert_equal() {- local expected="$1"- local actual="$2"- local message="$3"- if [ "${actual}" != "${expected}" ]; then- echo "FAIL: ${message}: expected=${expected}, actual=${actual}" >&2- exit 1- fi-}--main() {- check_cmd "yq"-- TEST_DIR="$(mktemp -d)"- local test_dir="${TEST_DIR}"- trap cleanup EXIT-- DEPLOY_VARS["OS_TYPE"]="linux"- DEPLOY_VARS["MODE"]="product"- DEPLOY_VARS["WEB_NODE_PORT"]="31001"- DEPLOY_VARS["MANAGER_SERVER_NODE_PORT"]="31002"- DEPLOY_VARS["MANAGER_WEB_NODE_PORT"]="31003"-- assert_equal \- "false" \- "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" \- "User Web embedding must be disabled by default"- printf '%s\n' 'ENABLE_USER_WEB_EMBEDDING=true' > "${test_dir}/.env.custom"- read_env_from_file "${test_dir}/.env.custom" "DEPLOY_VARS"- assert_equal \- "true" \- "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" \- ".env.custom compatibility value must be read"-- CONFIG["WEB_FILE"]="${test_dir}/web.yaml"-- DEPLOY_VARS["USER_WEB_MODE"]="personal"- DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="false"- gen_web_file- assert_equal \- "NodePort" \- "$(yq eval-all 'select(.metadata.name == "jiuwenclaw-web-nodeport") | .spec.type' "${CONFIG["WEB_FILE"]}")" \- "standalone mode must expose the User Web NodePort"- assert_equal \- "0.0.0.0" \- "$(yq eval-all 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "FRONTEND_HOST").value' "${CONFIG["WEB_FILE"]}")" \- "User Web frontend must listen on all interfaces"-- DEPLOY_VARS["USER_WEB_MODE"]="enterprise"- DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="true"- gen_web_file- assert_equal \- "0" \- "$(yq eval-all '[select(.metadata.name == "jiuwenclaw-web-nodeport")] | length' "${CONFIG["WEB_FILE"]}")" \- "enterprise mode must not expose the User Web NodePort"-- DEPLOY_VARS["IS_UP_MANAGER_WEB"]="false"- if (check_user_web_mode_config) >/dev/null 2>&1; then- echo "FAIL: embedded mode must require Manager Web" >&2- exit 1- fi-- DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"- check_user_web_mode_config-- DEPLOY_VARS["USER_WEB_MODE"]="invalid"- if (check_user_web_mode_config) >/dev/null 2>&1; then- echo "FAIL: invalid boolean value must be rejected" >&2- exit 1- fi-- CONFIG["MANAGER_SERVER_FILE"]="${test_dir}/manager-server.yaml"- render_config_template \- "${CONFIG["MANAGER_SERVER_TEMPLATE_FILE"]}" \- "${CONFIG["MANAGER_SERVER_FILE"]}" \- "DEPLOY_VARS"- assert_equal \- "http://jiuwenclaw-identity:8770/v1/auth/public_key" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_PUBLIC_KEY_URL").value' "${CONFIG["MANAGER_SERVER_FILE"]}")" \- "Manager Server must receive the Identity public-key URL"-- CONFIG["IDENTITY_FILE"]="${test_dir}/identity.yaml"- render_config_template \- "${CONFIG["IDENTITY_TEMPLATE_FILE"]}" \- "${CONFIG["IDENTITY_FILE"]}" \- "DEPLOY_VARS"- assert_equal \- "false" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_DEMO_ENABLED").value' "${CONFIG["IDENTITY_FILE"]}")" \- "Identity federation Demo must remain disabled by default"- assert_equal \- "/idp" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX").value' "${CONFIG["IDENTITY_FILE"]}")" \- "Identity federation browser URLs must use the Manager Web IDP prefix"- assert_equal \- "300" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_REQUEST_TTL").value' "${CONFIG["IDENTITY_FILE"]}")" \- "Identity federation request TTL must be rendered"- assert_equal \- "60" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_CODE_TTL").value' "${CONFIG["IDENTITY_FILE"]}")" \- "Identity federation code TTL must be rendered"- assert_equal \- "enterprise-admins" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_DEMO_ADMIN_GROUP").value' "${CONFIG["IDENTITY_FILE"]}")" \- "Identity federation admin group must be rendered"-- CONFIG["MANAGER_WEB_FILE"]="${test_dir}/manager-web.yaml"- render_config_template \- "${CONFIG["MANAGER_WEB_TEMPLATE_FILE"]}" \- "${CONFIG["MANAGER_WEB_FILE"]}" \- "DEPLOY_VARS"- assert_equal \- "0" \- "$(yq eval-all '[select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_PUBLIC_KEY_URL")] | length' "${CONFIG["MANAGER_WEB_FILE"]}")" \- "Manager Web must not receive the unused public-key URL"- assert_equal \- "http://jiuwenclaw-web:5173" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_USER_WEB_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \- "Manager Web must route /chat to the User Web HTTP service"- assert_equal \- "http://jiuwenclaw-gateway:19002" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_HTTP_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \- "Manager Web must route HTTP/SSE to the Gateway Web HTTP service"- assert_equal \- "http://jiuwenclaw-gateway:19000" \- "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_WS_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \- "Manager Web must route WebSocket to the Gateway WebSocket service"- assert_equal \- "0" \- "$(yq eval-all '[select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_SSE" or .name == "MANAGER_WEB_USER_SERVER_TARGET")] | length' "${CONFIG["MANAGER_WEB_FILE"]}")" \- "obsolete Manager Web proxy variables must not be rendered"- assert_equal \- "5173" \- "$(yq eval-all 'select(.kind == "Service" and .metadata.name == "jiuwenclaw-web").spec.ports[] | select(.name == "http").port' "${CONFIG["WEB_FILE"]}")" \- "User Web ClusterIP service must expose its HTTP port"-- CONFIG["GATEWAY_FILE"]="${test_dir}/gateway.yaml"- render_config_template \- "${CONFIG["GATEWAY_TEMPLATE_FILE"]}" \- "${CONFIG["GATEWAY_FILE"]}" \- "DEPLOY_VARS"- assert_equal \- "1" \- "$(yq eval-all '[select(.kind == "Service" and .metadata.name == "jiuwenclaw-gateway").spec.ports[] | select(.port == 19001)] | length' "${CONFIG["GATEWAY_FILE"]}")" \- "Gateway Service must expose its shared HTTP and ACP listener only once"- assert_equal \- "http" \- "$(yq eval-all 'select(.kind == "Service" and .metadata.name == "jiuwenclaw-gateway").spec.ports[] | select(.port == 19001).name' "${CONFIG["GATEWAY_FILE"]}")" \- "Gateway shared listener must use the HTTP service port"-- ensure_secret_configmap() { :; }- delete_k8s_resource() { :; }- exec_cmd() { :; }- wait_k8s_resource_ready() { :; }- success() { :; }-- DEPLOY_VARS["USER_WEB_MODE"]="enterprise"- deploy_web- DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"- deploy_manager-- echo "PASS: identity and User Web deployment checks"-}--main "$@"diff --git a/deploy/enterprise/web_handler.sh b/deploy/enterprise/web_handler.shindex 2a9e44b491..3dfa3b2a20 100755--- a/deploy/enterprise/web_handler.sh+++ b/deploy/enterprise/web_handler.sh@@ -46,6 +46,16 @@ gen_web_file() {}]' -i "${file}"+ if [ "${DEPLOY_VARS["DB_TYPE"]}" == "postgresql" ]; then+ yq eval '+ select(.kind == "Deployment").spec.template.spec.containers[0].env += [+ {+ "name": "WEB_PG_SCHEMA",+ "value": "'"${DEPLOY_VARS["WEB_PG_SCHEMA"]}"'"+ }+ ]' -i "${file}"+ fi+add_resource_if_set "WEB" "${file}"# yq 追加资源配置时可能重复 env;Deployment strategic merge patch 不接受重复键,diff --git a/jiuwenswarm/agents/harness/common/memory/__init__.py b/jiuwenswarm/agents/harness/common/memory/__init__.pyindex f8e4affd09..76940f608e 100644--- a/jiuwenswarm/agents/harness/common/memory/__init__.py+++ b/jiuwenswarm/agents/harness/common/memory/__init__.py@@ -18,7 +18,6 @@ from .config import (get_embed_config,clear_embed_config_db_cache,set_embed_config_db_cache,- reload_embed_config_from_gateway_db,clear_task_memory_config_db_cache,get_task_memory_config,reload_task_memory_config_from_gateway_db,@@ -80,7 +79,6 @@ __all__ = ["get_embed_config","clear_embed_config_db_cache","set_embed_config_db_cache",- "reload_embed_config_from_gateway_db","clear_task_memory_config_db_cache","get_task_memory_config","reload_task_memory_config_from_gateway_db",diff --git a/jiuwenswarm/agents/harness/common/memory/config.py b/jiuwenswarm/agents/harness/common/memory/config.pyindex 99261c595b..f747fc4bf7 100644--- a/jiuwenswarm/agents/harness/common/memory/config.py+++ b/jiuwenswarm/agents/harness/common/memory/config.py@@ -519,40 +519,6 @@ def get_memory_mode(config: Optional[Dict[str, Any]] = None) -> str:return "cloud" if mode == "cloud" else "local"-async def reload_embed_config_from_gateway_db() -> None:- """从 Gateway 库加载 ``embed_config`` 并刷新 embedding 缓存(企业版)。"""- global _embed_config_db_cache- if not is_enterprise():- return- try:- from jiuwenswarm.server.runtime.enterprise_config import gateway_db-- jid = gateway_db.resolve_jiuwenclaw_id()- if not jid:- _embed_config_db_cache = None- return-- rows = await gateway_db.list_records(- "embed_config",- filters={"jiuwenclaw_id": jid},- )- row = rows[0] if rows else None- if row is not None:- _embed_config_db_cache = {- "api_key": row.get("embed_api_key"),- "base_url": row.get("embed_base_url"),- "model": row.get("embed_model"),- }- else:- _embed_config_db_cache = None- except Exception as exc: # noqa: BLE001- logger.warning(- "embed_config read failed: %s",- exc,- exc_info=True,- )--def clear_task_memory_config_db_cache() -> None:"""清除 task_memory_config 的 DB 缓存,使下次重新从 DB 读取."""global _task_memory_config_db_cachediff --git a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.pyindex 36e99530e4..f69a6fe152 100644--- a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py+++ b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py@@ -365,7 +365,7 @@ def persist_permissions_mutate(mutate_fn(permissions)- if is_enterprise() and _gateway_db_available():+ if is_enterprise():if _event_loop_is_running():loop = asyncio.get_running_loop()task = loop.create_task(@@ -404,16 +404,6 @@ def _persist_permissions_to_yaml(permissions: dict[str, Any]) -> None:dump_yaml_round_trip(CONFIG_YAML_PATH, data)clear_permissions_config_cache()--def _gateway_db_available() -> bool:- try:- from jiuwenswarm.server.runtime.enterprise_config import gateway_db-- return gateway_db.is_gateway_db_available()- except Exception: # noqa: BLE001- return False--async def _load_permissions_body_from_db() -> dict[str, Any] | None:from jiuwenswarm.server.runtime.enterprise_config import gateway_dbdiff --git a/jiuwenswarm/channels/web/history_store.py b/jiuwenswarm/channels/web/history_store.pydeleted file mode 100644index 86e2a8b435..0000000000--- a/jiuwenswarm/channels/web/history_store.py+++ /dev/null@@ -1,911 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.--"""会话历史采集与查询。--写路径可来自:-- ``app_web`` WS 反代(``HistoryFrameRunner``)-- Gateway ``WebChannel`` Listen(无 Pod 时的主路径)--存储按库类型分支:-- ``sqlite``:本地 ``web_history.db``(``WEB_SQLITE_PATH`` 可覆盖;兼容旧名 ``WEB_HISTORY_SQLITE_PATH``)-- ``mysql``:独立库 ``web``(``WEB_DB_*``);缺 ``WEB_DB_HOST`` 则不可用,不回退 SQLite-- ``postgresql`` 等:暂不支持,明确不可用--选型与 Gateway ``GATEWAY_DB_TYPE`` 对齐:``WEB_DB_TYPE`` → ``DB_TYPE`` →-已配 ``WEB_DB_HOST`` 则视为 mysql → 按 ``DEPLOYMENT_MODE``(企业主备/分布式 mysql,standalone sqlite)。-"""--from __future__ import annotations--import asyncio-import json-import logging-import os-import sqlite3-import threading-import time-from dataclasses import dataclass-from pathlib import Path-from typing import Any, Awaitable, Callable, Literal--logger = logging.getLogger("jiuwenswarm.web.history")--_REQUEST_METHODS = frozenset({"chat.send", "chat.resume", "chat.user_answer"})-_FINAL_EVENTS = frozenset({"chat.final", "chat.error"})--_TITLE_LEN = 30-_PREVIEW_LEN = 100-_MAX_LIST_LIMIT = 100--FrameCallback = Callable[[str, str, "str | None"], Awaitable[None]]-HistoryBackend = Literal["memory", "sqlite", "mysql"]--_DEFAULT_DB_NAME = "web"-_DEFAULT_SQLITE_NAME = "web_history.db"--_CREATE_DATABASE_SQL = (- "CREATE DATABASE IF NOT EXISTS `{db}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"-)--_MYSQL_CREATE_TABLES_SQL = """-CREATE TABLE IF NOT EXISTS sessions (- session_id VARCHAR(128) NOT NULL,- user VARCHAR(128) NOT NULL DEFAULT 'guest',- title VARCHAR(255) NULL,- message_count INT NOT NULL DEFAULT 0,- last_preview TEXT NULL,- created_at DOUBLE NOT NULL,- updated_at DOUBLE NOT NULL,- PRIMARY KEY (session_id),- KEY idx_sessions_user_updated (user, updated_at)-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;-CREATE TABLE IF NOT EXISTS messages (- id BIGINT NOT NULL AUTO_INCREMENT,- session_id VARCHAR(128) NOT NULL,- request_id VARCHAR(128) NOT NULL,- role VARCHAR(32) NOT NULL,- content MEDIUMTEXT NOT NULL,- event_type VARCHAR(64) NULL,- timestamp DOUBLE NOT NULL,- PRIMARY KEY (id),- UNIQUE KEY uk_msg_sid_rid_role (session_id, request_id, role),- KEY idx_msg_session_ts (session_id, timestamp)-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;-"""--_MYSQL_INSERT_MESSAGE_SQL = (- "INSERT IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "- "VALUES (%s, %s, %s, %s, %s, %s)"-)--_MYSQL_UPSERT_SESSION_SQL = """-INSERT INTO sessions (session_id, user, title, message_count, last_preview, created_at, updated_at)-VALUES (%s, %s, %s, 1, %s, %s, %s)-ON DUPLICATE KEY UPDATE- message_count = message_count + 1,- last_preview = VALUES(last_preview),- updated_at = VALUES(updated_at),- title = COALESCE(title, VALUES(title))-"""--_SQLITE_SCHEMA = """-CREATE TABLE IF NOT EXISTS sessions (- session_id TEXT PRIMARY KEY,- user TEXT,- title TEXT,- message_count INTEGER DEFAULT 0,- last_preview TEXT,- created_at REAL NOT NULL,- updated_at REAL NOT NULL-);-CREATE TABLE IF NOT EXISTS messages (- id INTEGER PRIMARY KEY AUTOINCREMENT,- session_id TEXT NOT NULL,- request_id TEXT NOT NULL,- role TEXT NOT NULL,- content TEXT NOT NULL,- event_type TEXT,- timestamp REAL NOT NULL,- UNIQUE(session_id, request_id, role)-);-CREATE INDEX IF NOT EXISTS idx_msg_session_ts ON messages(session_id, timestamp);-"""--_SQLITE_INSERT_MESSAGE_SQL = (- "INSERT OR IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "- "VALUES (?, ?, ?, ?, ?, ?)"-)--_SQLITE_UPSERT_SESSION_SQL = """-INSERT INTO sessions (session_id, user, title, message_count, last_preview, created_at, updated_at)-VALUES (?, ?, ?, 1, ?, ?, ?)-ON CONFLICT(session_id) DO UPDATE SET- message_count = message_count + 1,- last_preview = excluded.last_preview,- updated_at = excluded.updated_at,- title = COALESCE(sessions.title, excluded.title)-"""---def _env(*names: str, default: str = "") -> str:- for name in names:- raw = os.getenv(name)- if raw is not None and str(raw).strip():- return str(raw).strip()- return default---def resolve_history_db_type() -> str:- """解析 Web 会话历史库类型。-- 优先级:``WEB_DB_TYPE`` → ``DB_TYPE`` → 已配 ``WEB_DB_HOST`` 则 ``mysql`` →- 按 ``DEPLOYMENT_MODE``(企业主备/分布式 ``mysql``,standalone ``sqlite``)。- """- explicit = _env("WEB_DB_TYPE") or _env("DB_TYPE")- if explicit:- return explicit.strip().lower()- if _env("WEB_DB_HOST"):- return "mysql"- try:- from jiuwenswarm.deployment_mode import (- history_storage_backend,- normalize_deployment_mode,- )-- mode = normalize_deployment_mode(os.getenv("DEPLOYMENT_MODE", "standalone"))- return history_storage_backend(mode)- except Exception:- return "sqlite"---def default_history_sqlite_path() -> Path:- """SQLite 历史默认路径;``WEB_SQLITE_PATH`` 可覆盖,兼容旧名 ``WEB_HISTORY_SQLITE_PATH``。"""- override = _env("WEB_SQLITE_PATH", "WEB_HISTORY_SQLITE_PATH")- if override:- return Path(override).expanduser().resolve()- from jiuwenswarm.common.utils import (- get_multi_tenant_user_workspace_dir,- get_user_workspace_dir,- )-- tenant_root = get_multi_tenant_user_workspace_dir("default", "default")- return (tenant_root or get_user_workspace_dir()) / _DEFAULT_SQLITE_NAME---def default_enterprise_history_db_path() -> str:- """兼容旧调用:返回 sqlite 默认路径字符串。"""- return str(default_history_sqlite_path())---@dataclass(frozen=True)-class WebHistoryDbSettings:- """Web 历史库 MySQL 连接(独立 database ``web``)。"""-- host: str- port: int- user: str- password: str- database: str = _DEFAULT_DB_NAME-- @classmethod- def from_env(cls) -> WebHistoryDbSettings | None:- host = _env("WEB_DB_HOST")- if not host:- return None- port_raw = _env("WEB_DB_PORT", default="3306")- try:- port = int(port_raw)- except ValueError:- port = 3306- return cls(- host=host,- port=port,- user=_env("WEB_DB_USER", default="root"),- password=_env("WEB_DB_PASSWORD"),- database=_env("WEB_DB_NAME", default=_DEFAULT_DB_NAME) or _DEFAULT_DB_NAME,- )---def _quote_ident(name: str) -> str:- cleaned = "".join(ch for ch in name if ch.isalnum() or ch in {"_", "$"})- return cleaned or _DEFAULT_DB_NAME---class ChatHistoryStore:- """会话历史存储:SQLite / MySQL;单测可用 memory=True。"""-- def __init__(- self,- settings: WebHistoryDbSettings | str | Path | None = None,- *,- db_path: str | Path | None = None,- memory: bool = False,- ) -> None:- if isinstance(settings, (str, Path)):- db_path = settings- settings = None- self._settings = settings- self._db_path = Path(db_path) if db_path is not None else None- self._memory = memory- self._ready = False- self._init_lock = threading.Lock()- self._mem_lock = threading.Lock()- self._mem_sessions: dict[str, dict[str, Any]] = {}- self._mem_messages: list[dict[str, Any]] = []-- @classmethod- def for_db_type(cls, db_type: str) -> ChatHistoryStore:- normalized = str(db_type or "").strip().lower() or "sqlite"- if normalized in ("postgresql", "postgres", "pg"):- logger.warning(- "[history] Web 会话历史暂不支持 PostgreSQL(db_type=%s),历史不可用(不回退 SQLite)",- normalized,- )- return cls(settings=None, memory=False)- if normalized == "mysql":- return cls(settings=WebHistoryDbSettings.from_env(), memory=False)- if normalized == "sqlite":- return cls(db_path=default_history_sqlite_path(), memory=False)- logger.warning(- "[history] 不支持的历史库类型 %r,会话历史不可用(不回退 SQLite)",- normalized,- )- return cls(settings=None, memory=False)-- @classmethod- def from_env(cls) -> ChatHistoryStore:- return cls.for_db_type(resolve_history_db_type())-- @classmethod- def memory(cls) -> ChatHistoryStore:- return cls(settings=None, db_path=None, memory=True)-- @property- def backend(self) -> HistoryBackend:- if self._memory:- return "memory"- if self._db_path is not None:- return "sqlite"- return "mysql"-- @property- def db_path(self) -> Path | None:- return self._db_path-- @property- def mysql_settings(self) -> WebHistoryDbSettings | None:- return self._settings-- @property- def available(self) -> bool:- if self._memory:- return True- if self._db_path is not None:- return True- return self._settings is not None-- def _connect_mysql(self, *, with_database: bool):- import pymysql-- if self._settings is None:- raise RuntimeError("MySQL settings 未配置,无法建立连接")- kwargs: dict[str, Any] = {- "host": self._settings.host,- "port": self._settings.port,- "user": self._settings.user,- "password": self._settings.password,- "charset": "utf8mb4",- "autocommit": False,- "cursorclass": pymysql.cursors.DictCursor,- }- if with_database:- kwargs["database"] = self._settings.database- return pymysql.connect(**kwargs)-- def _connect_sqlite(self) -> sqlite3.Connection:- if self._db_path is None:- raise RuntimeError("SQLite db_path 未配置,无法建立连接")- conn = sqlite3.connect(str(self._db_path), check_same_thread=False)- conn.row_factory = sqlite3.Row- return conn-- def _ensure_schema(self) -> bool:- if self._memory:- return True- if self.backend == "sqlite":- return self._ensure_sqlite_schema()- return self._ensure_mysql_schema()-- def _ensure_sqlite_schema(self) -> bool:- if self._db_path is None:- logger.error("[history] SQLite 未配置 db_path,会话历史不可用")- return False- if self._ready:- return True- with self._init_lock:- if self._ready:- return True- try:- self._db_path.parent.mkdir(parents=True, exist_ok=True)- conn = self._connect_sqlite()- try:- conn.execute("PRAGMA journal_mode=WAL")- conn.execute("PRAGMA foreign_keys=ON")- conn.executescript(_SQLITE_SCHEMA)- try:- conn.execute("ALTER TABLE sessions ADD COLUMN user TEXT")- except sqlite3.OperationalError as e:- if "duplicate column" not in str(e).lower():- raise- logger.debug("[history] sessions.user 列已存在,跳过 ALTER")- conn.execute("UPDATE sessions SET user = 'guest' WHERE user IS NULL")- conn.commit()- finally:- conn.close()- self._ready = True- logger.info("[history] SQLite store 初始化完成 db=%s", self._db_path)- return True- except Exception:- logger.exception("[history] SQLite 初始化失败,会话历史暂不可用")- return False-- def _ensure_mysql_schema(self) -> bool:- if self._settings is None:- logger.error("[history] MySQL 未配置(缺少 WEB_DB_HOST),会话历史不可用")- return False- if self._ready:- return True- with self._init_lock:- if self._ready:- return True- db_name = _quote_ident(self._settings.database)- try:- conn = self._connect_mysql(with_database=False)- try:- with conn.cursor() as cur:- cur.execute(_CREATE_DATABASE_SQL.format(db=db_name))- conn.commit()- finally:- conn.close()- conn = self._connect_mysql(with_database=True)- try:- with conn.cursor() as cur:- for stmt in _MYSQL_CREATE_TABLES_SQL.split(";"):- sql = stmt.strip()- if sql:- cur.execute(sql)- conn.commit()- finally:- conn.close()- self._ready = True- logger.info(- "[history] MySQL store 初始化完成 %s:%s/%s",- self._settings.host,- self._settings.port,- self._settings.database,- )- return True- except Exception:- logger.exception("[history] MySQL 初始化失败,会话历史暂不可用")- return False-- def _run_write(self, fn: Callable[[Any], bool]) -> bool:- if self._memory:- return fn(None)- if not self._ensure_schema():- return False- try:- if self.backend == "sqlite":- conn = self._connect_sqlite()- try:- inserted = fn(conn)- conn.commit()- return inserted- finally:- conn.close()- conn = self._connect_mysql(with_database=True)- try:- inserted = fn(conn)- conn.commit()- return inserted- finally:- conn.close()- except Exception:- logger.exception("[history] %s 写入失败", self.backend.upper())- return False-- async def _run_write_async(self, fn: Callable[[Any], bool]) -> bool:- return await asyncio.to_thread(self._run_write, fn)-- def _insert_message_and_upsert_session(- self,- conn: Any,- *,- session_id: str,- request_id: str,- role: str,- content: str,- event_type: str | None,- ts: float,- user: str | None,- title: str | None,- preview: str,- ) -> bool:- if self._memory:- key = (session_id, request_id, role)- with self._mem_lock:- if any(- (m["session_id"], m["request_id"], m["role"]) == key- for m in self._mem_messages- ):- return False- self._mem_messages.append({- "session_id": session_id,- "request_id": request_id,- "role": role,- "content": content,- "event_type": event_type,- "timestamp": ts,- })- existing = self._mem_sessions.get(session_id)- if existing is None:- self._mem_sessions[session_id] = {- "session_id": session_id,- "user": user or "guest",- "title": title,- "message_count": 1,- "last_preview": preview,- "created_at": ts,- "updated_at": ts,- }- else:- existing["message_count"] = int(existing.get("message_count") or 0) + 1- existing["last_preview"] = preview- existing["updated_at"] = ts- if not existing.get("title") and title:- existing["title"] = title- return True-- if self.backend == "sqlite":- cur = conn.execute(- _SQLITE_INSERT_MESSAGE_SQL,- (session_id, request_id, role, content, event_type, ts),- )- inserted = cur.rowcount > 0- if inserted:- conn.execute(- _SQLITE_UPSERT_SESSION_SQL,- (session_id, user or "guest", title, preview, ts, ts),- )- return inserted-- with conn.cursor() as cur:- cur.execute(- _MYSQL_INSERT_MESSAGE_SQL,- (session_id, request_id, role, content, event_type, ts),- )- inserted = cur.rowcount > 0- if inserted:- cur.execute(- _MYSQL_UPSERT_SESSION_SQL,- (session_id, user or "guest", title, preview, ts, ts),- )- return inserted-- async def record_user(- self,- *,- request_id: str,- session_id: str,- query: str,- ts: float,- user: str | None = None,- ) -> bool:- if not user:- user = "guest"- title = query[:_TITLE_LEN]- preview = query[:_PREVIEW_LEN]- inserted = await self._run_write_async(- lambda conn: self._insert_message_and_upsert_session(- conn,- session_id=session_id,- request_id=request_id,- role="user",- content=query,- event_type=None,- ts=ts,- user=user,- title=title,- preview=preview,- )- )- if inserted:- logger.info(- "[history] 落盘 user: rid=%s sid=%s user=%s len=%d",- request_id, session_id, user, len(query),- )- return inserted-- async def record_assistant(- self,- *,- request_id: str,- session_id: str,- content: str,- event_type: str,- ts: float,- ) -> bool:- preview = content[:_PREVIEW_LEN]- inserted = await self._run_write_async(- lambda conn: self._insert_message_and_upsert_session(- conn,- session_id=session_id,- request_id=request_id,- role="assistant",- content=content,- event_type=event_type,- ts=ts,- user="guest",- title=None,- preview=preview,- )- )- if inserted:- logger.info(- "[history] 落盘 assistant: rid=%s sid=%s event=%s len=%d",- request_id, session_id, event_type, len(content),- )- return inserted-- def list_sessions_blocking(- self, *, limit: int, offset: int, user: str | None,- ) -> list[dict[str, Any]]:- limit = max(1, min(limit, _MAX_LIST_LIMIT))- offset = max(0, offset)- if not user:- user = "guest"- if self._memory:- with self._mem_lock:- rows = [- dict(s) for s in self._mem_sessions.values()- if s.get("user") == user- ]- rows.sort(key=lambda r: float(r.get("updated_at") or 0), reverse=True)- return rows[offset:offset + limit]- if not self._ensure_schema():- return []- if self.backend == "sqlite":- try:- conn = self._connect_sqlite()- try:- rows = conn.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE user = ? ORDER BY updated_at DESC LIMIT ? OFFSET ?",- (user, limit, offset),- ).fetchall()- return [dict(r) for r in rows]- finally:- conn.close()- except Exception:- logger.exception("[history] SQLite 读取会话列表失败")- return []- try:- conn = self._connect_mysql(with_database=True)- try:- with conn.cursor() as cur:- cur.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE user = %s ORDER BY updated_at DESC LIMIT %s OFFSET %s",- (user, limit, offset),- )- return list(cur.fetchall() or [])- finally:- conn.close()- except Exception:- logger.exception("[history] MySQL 读取会话列表失败")- return []-- def get_session_detail_blocking(- self, session_id: str, *, user: str | None,- ) -> dict[str, Any] | None:- if not user:- user = "guest"- if self._memory:- with self._mem_lock:- s = self._mem_sessions.get(session_id)- if s is None or s.get("user") != user:- return None- msgs = [- {- "role": m["role"],- "content": m["content"],- "event_type": m["event_type"],- "timestamp": m["timestamp"],- "request_id": m["request_id"],- }- for m in self._mem_messages- if m["session_id"] == session_id- ]- msgs.sort(key=lambda m: float(m.get("timestamp") or 0))- return {**s, "messages": msgs}- if not self._ensure_schema():- return None- if self.backend == "sqlite":- try:- conn = self._connect_sqlite()- try:- s = conn.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE session_id = ? AND user = ?",- (session_id, user),- ).fetchone()- if s is None:- return None- msgs = conn.execute(- "SELECT role, content, event_type, timestamp, request_id "- "FROM messages WHERE session_id = ? ORDER BY timestamp ASC",- (session_id,),- ).fetchall()- return {**dict(s), "messages": [dict(m) for m in msgs]}- finally:- conn.close()- except Exception:- logger.exception("[history] SQLite 读取会话详情失败")- return None- try:- conn = self._connect_mysql(with_database=True)- try:- with conn.cursor() as cur:- cur.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE session_id = %s AND user = %s",- (session_id, user),- )- s = cur.fetchone()- if s is None:- return None- cur.execute(- "SELECT role, content, event_type, timestamp, request_id "- "FROM messages WHERE session_id = %s ORDER BY timestamp ASC",- (session_id,),- )- msgs = list(cur.fetchall() or [])- return {**s, "messages": msgs}- finally:- conn.close()- except Exception:- logger.exception("[history] MySQL 读取会话详情失败")- return None-- async def list_sessions(self, *, limit: int = 20, offset: int = 0) -> list[dict[str, Any]]:- return await asyncio.to_thread(- self.list_sessions_blocking, limit=limit, offset=offset, user=None,- )-- async def get_session_detail(self, session_id: str) -> dict[str, Any] | None:- return await asyncio.to_thread(- self.get_session_detail_blocking, session_id, user=None,- )-- async def close(self) -> None:- self._ready = False- logger.info("[history] store 已关闭 backend=%s", self.backend)---def make_history_callback(store: ChatHistoryStore) -> FrameCallback:- """产出 on_frame 回调:白名单 → pending 回填 → store.record_*。"""- pending: dict[str, dict[str, Any]] = {}- assistant_buf: dict[str, str] = {}-- async def _handle_browser(data: dict[str, Any]) -> None:- if data.get("type") != "req":- return- method = data.get("method")- if method not in _REQUEST_METHODS:- return- params = data.get("params") if isinstance(data.get("params"), dict) else {}- query = params.get("query") or params.get("content")- if not isinstance(query, str) or not query:- return- request_id = data.get("id")- if not isinstance(request_id, str):- return- session_id = params.get("session_id")- user = params.get("user") or params.get("user_id")- if not isinstance(user, str) or not user.strip():- user = None- else:- user = user.strip()- ts = time.time()- if isinstance(session_id, str) and session_id:- await store.record_user(- request_id=request_id, session_id=session_id, query=query, ts=ts, user=user,- )- else:- pending[request_id] = {"query": query, "ts": ts, "method": method, "user": user}- logger.debug(- "[history] 暂存 pending user(无 sid): rid=%s method=%s pending=%d",- request_id, method, len(pending),- )-- async def _handle_uplink(data: dict[str, Any]) -> None:- if data.get("type") != "event":- return- event = data.get("event")- payload = data.get("payload") if isinstance(data.get("payload"), dict) else {}- request_id = data.get("request_id")- if not isinstance(request_id, str) or not request_id:- payload_rid = payload.get("request_id")- if isinstance(payload_rid, str) and payload_rid:- request_id = payload_rid-- if event == "chat.delta" and isinstance(request_id, str):- delta = payload.get("content")- if isinstance(delta, str) and delta:- assistant_buf[request_id] = assistant_buf.get(request_id, "") + delta- return-- if event not in _FINAL_EVENTS:- return- session_id = payload.get("session_id")- if not isinstance(session_id, str) or not session_id:- logger.warning(- "[history] 终态帧缺 session_id,丢弃: event=%s rid=%s",- event, request_id if isinstance(request_id, str) else "",- )- return- if event == "chat.final":- content = assistant_buf.pop(request_id, "") or payload.get("content") or ""- else:- content = payload.get("error") or payload.get("content") or assistant_buf.pop(request_id, "")- if not isinstance(content, str) or not content:- logger.debug("[history] 终态帧无内容,丢弃: event=%s rid=%s", event, request_id)- return- ts = time.time()- if isinstance(request_id, str) and request_id in pending:- p = pending.pop(request_id)- await store.record_user(- request_id=request_id, session_id=session_id,- query=p["query"], ts=p["ts"], user=p.get("user"),- )- logger.info("[history] pending 回填 user: rid=%s sid=%s", request_id, session_id)- await store.record_assistant(- request_id=request_id if isinstance(request_id, str) else "",- session_id=session_id, content=content, event_type=event, ts=ts,- )-- async def cb(direction: str, raw: str, conn_id: str | None = None) -> None: # noqa: ARG001- try:- data = json.loads(raw)- except json.JSONDecodeError:- logger.debug("[history] 非 JSON 帧,忽略: dir=%s head=%r", direction, (raw or "")[:120])- return- if not isinstance(data, dict):- return- try:- if direction == "browser":- await _handle_browser(data)- elif direction == "uplink":- await _handle_uplink(data)- except Exception:- logger.exception("[history] on_frame 处理失败: dir=%s", direction)-- return cb---_default_store: ChatHistoryStore | None = None-_default_store_lock = threading.Lock()---def get_default_store() -> ChatHistoryStore:- """进程内单例,避免 HTTP 每次请求重建库。"""- global _default_store- with _default_store_lock:- if _default_store is None:- _default_store = ChatHistoryStore.from_env()- return _default_store---def set_default_store(store: ChatHistoryStore) -> None:- global _default_store- with _default_store_lock:- _default_store = store---def _coerce_store(store: ChatHistoryStore | str | Path | None) -> ChatHistoryStore | None:- if store is None:- st = get_default_store()- return st if st.available else None- if isinstance(store, ChatHistoryStore):- return store if store.available else None- path = Path(store)- if not path.exists():- return None- return ChatHistoryStore(db_path=path)---def list_sessions_sync(- store: ChatHistoryStore | str | Path | None = None,- *,- limit: int = 20,- offset: int = 0,- user: str | None = None,-) -> list[dict[str, Any]]:- """同步读会话列表(http.server 线程用)。库不可用返回空。"""- st = _coerce_store(store)- if st is None:- return []- return st.list_sessions_blocking(limit=limit, offset=offset, user=user)---def _is_legacy_db_path_call(- session_id: str | Path,- store: ChatHistoryStore | str | Path | None,-) -> bool:- if isinstance(session_id, Path):- return True- if store is None or isinstance(store, ChatHistoryStore):- return False- return isinstance(session_id, str) and session_id.endswith(".db")---def get_session_detail_sync(- session_id: str | Path,- store: ChatHistoryStore | str | Path | None = None,- *,- user: str | None = None,-) -> dict[str, Any] | None:- """同步读会话详情。兼容旧调用 ``(db_path, session_id)``。"""- if _is_legacy_db_path_call(session_id, store):- db_path, sid = session_id, str(store or "")- if not sid:- return None- st = _coerce_store(db_path)- if st is None:- return None- return st.get_session_detail_blocking(sid, user=user)- if not session_id:- return None- st = _coerce_store(store)- if st is None:- return None- return st.get_session_detail_blocking(str(session_id), user=user)---class HistoryFrameRunner:- """Run async history callbacks from sync WS proxy / Listen enqueue threads."""-- def __init__(self, store: ChatHistoryStore) -> None:- self._callback = make_history_callback(store)- self._loop = asyncio.new_event_loop()- self._thread = threading.Thread(target=self._run_loop, name="web-history", daemon=True)- self._started = False-- def _run_loop(self) -> None:- asyncio.set_event_loop(self._loop)- self._loop.run_forever()-- def start(self) -> None:- if self._started:- return- self._thread.start()- self._started = True-- def submit(self, direction: str, raw: str) -> None:- if not self._started:- return- try:- asyncio.run_coroutine_threadsafe(self._callback(direction, raw, None), self._loop)- except Exception:- logger.warning("[history] submit frame failed dir=%s", direction, exc_info=True)-- def stop(self) -> None:- if not self._started:- return- try:- self._loop.call_soon_threadsafe(self._loop.stop)- except Exception: # noqa: BLE001- logger.debug("[history] stop loop failed", exc_info=True)- if self._thread.is_alive():- self._thread.join(timeout=5.0)- self._started = Falsediff --git a/jiuwenswarm/channels/web/history_store/__init__.py b/jiuwenswarm/channels/web/history_store/__init__.pynew file mode 100644index 0000000000..5c0926ff9f--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/__init__.py@@ -0,0 +1,38 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 会话历史库包:个人版纯内存 / 企业版 mysql·pg 经 foundation DB-actor。++公开 API(保 ``from jiuwenswarm.channels.web.history_store import ...`` 路径不变):+- ``ChatHistoryStore`` / ``HistoryBackend``+- ``HistoryFrameRunner`` / ``make_history_callback`` / ``FrameCallback``+- ``set_default_store`` / ``get_default_store``+- ``list_sessions_sync`` / ``get_session_detail_sync``++个人版(memory)仅加载 ``settings``/``store``/``callback``/``api``,不 import foundation;+``tables``/``db_actor`` 仅企业版远程路径惰性加载。+"""++from __future__ import annotations++from .api import (+ get_default_store,+ get_session_detail_sync,+ list_sessions_sync,+ set_default_store,+)+from .callback import FrameCallback, HistoryFrameRunner, make_history_callback+from .settings import resolve_history_db_type+from .store import ChatHistoryStore, HistoryBackend++__all__ = [+ "ChatHistoryStore",+ "HistoryBackend",+ "HistoryFrameRunner",+ "make_history_callback",+ "FrameCallback",+ "set_default_store",+ "get_default_store",+ "list_sessions_sync",+ "get_session_detail_sync",+ "resolve_history_db_type",+]diff --git a/jiuwenswarm/channels/web/history_store/api.py b/jiuwenswarm/channels/web/history_store/api.pynew file mode 100644index 0000000000..c9890cb6f3--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/api.py@@ -0,0 +1,66 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 会话历史公开同步 API(http.server / fastapi 线程用)。"""++from __future__ import annotations++import threading+from typing import Any++from .store import ChatHistoryStore++_default_store: ChatHistoryStore | None = None+_default_store_lock = threading.Lock()+++def get_default_store() -> ChatHistoryStore:+ """进程内单例,避免 HTTP 每次请求重建库。"""+ global _default_store+ with _default_store_lock:+ if _default_store is None:+ _default_store = ChatHistoryStore.from_env()+ return _default_store+++def set_default_store(store: ChatHistoryStore) -> None:+ global _default_store+ with _default_store_lock:+ _default_store = store+++def _coerce_store(store: Any | None) -> ChatHistoryStore | None:+ if store is None:+ st = get_default_store()+ return st if st.available else None+ if isinstance(store, ChatHistoryStore):+ return store if store.available else None+ return None+++def list_sessions_sync(+ store: ChatHistoryStore | None = None,+ *,+ limit: int = 20,+ offset: int = 0,+ user: str | None = None,+) -> list[dict[str, Any]]:+ """同步读会话列表(http.server 线程用)。库不可用返回空。"""+ st = _coerce_store(store)+ if st is None:+ return []+ return st.list_sessions_blocking(limit=limit, offset=offset, user=user)+++def get_session_detail_sync(+ session_id: str,+ store: ChatHistoryStore | None = None,+ *,+ user: str | None = None,+) -> dict[str, Any] | None:+ """同步读会话详情。"""+ if not session_id:+ return None+ st = _coerce_store(store)+ if st is None:+ return None+ return st.get_session_detail_blocking(str(session_id), user=user)diff --git a/jiuwenswarm/channels/web/history_store/callback.py b/jiuwenswarm/channels/web/history_store/callback.pynew file mode 100644index 0000000000..252ea740c4--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/callback.py@@ -0,0 +1,166 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 会话历史帧回调与 ``HistoryFrameRunner``。++从同步 WS 代理 / Listen 入队线程把 async ``record_*`` 桥接到 store。+本模块不 import foundation。+"""++from __future__ import annotations++import asyncio+import json+import logging+import threading+import time+from typing import TYPE_CHECKING, Any, Awaitable, Callable++if TYPE_CHECKING:+ from .store import ChatHistoryStore++logger = logging.getLogger("jiuwenswarm.web.history")++_REQUEST_METHODS = frozenset({"chat.send", "chat.resume", "chat.user_answer"})+_FINAL_EVENTS = frozenset({"chat.final", "chat.error"})++FrameCallback = Callable[[str, str, "str | None"], Awaitable[None]]+++def make_history_callback(store: "ChatHistoryStore") -> FrameCallback:+ """产出 on_frame 回调:白名单 → pending 回填 → store.record_*。"""+ pending: dict[str, dict[str, Any]] = {}+ assistant_buf: dict[str, str] = {}++ async def _handle_browser(data: dict[str, Any]) -> None:+ if data.get("type") != "req":+ return+ method = data.get("method")+ if method not in _REQUEST_METHODS:+ return+ params = data.get("params") if isinstance(data.get("params"), dict) else {}+ query = params.get("query") or params.get("content")+ if not isinstance(query, str) or not query:+ return+ request_id = data.get("id")+ if not isinstance(request_id, str):+ return+ session_id = params.get("session_id")+ user = params.get("user") or params.get("user_id")+ if not isinstance(user, str) or not user.strip():+ user = None+ else:+ user = user.strip()+ ts = time.time()+ if isinstance(session_id, str) and session_id:+ await store.record_user(+ request_id=request_id, session_id=session_id, query=query, ts=ts, user=user,+ )+ else:+ pending[request_id] = {"query": query, "ts": ts, "method": method, "user": user}+ logger.debug(+ "[history] 暂存 pending user(无 sid): rid=%s method=%s pending=%d",+ request_id, method, len(pending),+ )++ async def _handle_uplink(data: dict[str, Any]) -> None:+ if data.get("type") != "event":+ return+ event = data.get("event")+ payload = data.get("payload") if isinstance(data.get("payload"), dict) else {}+ request_id = data.get("request_id")+ if not isinstance(request_id, str) or not request_id:+ payload_rid = payload.get("request_id")+ if isinstance(payload_rid, str) and payload_rid:+ request_id = payload_rid++ if event == "chat.delta" and isinstance(request_id, str):+ delta = payload.get("content")+ if isinstance(delta, str) and delta:+ assistant_buf[request_id] = assistant_buf.get(request_id, "") + delta+ return++ if event not in _FINAL_EVENTS:+ return+ session_id = payload.get("session_id")+ if not isinstance(session_id, str) or not session_id:+ logger.warning(+ "[history] 终态帧缺 session_id,丢弃: event=%s rid=%s",+ event, request_id if isinstance(request_id, str) else "",+ )+ return+ if event == "chat.final":+ content = assistant_buf.pop(request_id, "") or payload.get("content") or ""+ else:+ content = payload.get("error") or payload.get("content") or assistant_buf.pop(request_id, "")+ if not isinstance(content, str) or not content:+ logger.debug("[history] 终态帧无内容,丢弃: event=%s rid=%s", event, request_id)+ return+ ts = time.time()+ if isinstance(request_id, str) and request_id in pending:+ p = pending.pop(request_id)+ await store.record_user(+ request_id=request_id, session_id=session_id,+ query=p["query"], ts=p["ts"], user=p.get("user"),+ )+ logger.info("[history] pending 回填 user: rid=%s sid=%s", request_id, session_id)+ await store.record_assistant(+ request_id=request_id if isinstance(request_id, str) else "",+ session_id=session_id, content=content, event_type=event, ts=ts,+ )++ async def cb(direction: str, raw: str, conn_id: str | None = None) -> None: # noqa: ARG001+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ logger.debug("[history] 非 JSON 帧,忽略: dir=%s head=%r", direction, (raw or "")[:120])+ return+ if not isinstance(data, dict):+ return+ try:+ if direction == "browser":+ await _handle_browser(data)+ elif direction == "uplink":+ await _handle_uplink(data)+ except Exception:+ logger.exception("[history] on_frame 处理失败: dir=%s", direction)++ return cb+++class HistoryFrameRunner:+ """Run async history callbacks from sync WS proxy / Listen enqueue threads."""++ def __init__(self, store: "ChatHistoryStore") -> None:+ self._callback = make_history_callback(store)+ self._loop = asyncio.new_event_loop()+ self._thread = threading.Thread(target=self._run_loop, name="web-history", daemon=True)+ self._started = False++ def _run_loop(self) -> None:+ asyncio.set_event_loop(self._loop)+ self._loop.run_forever()++ def start(self) -> None:+ if self._started:+ return+ self._thread.start()+ self._started = True++ def submit(self, direction: str, raw: str) -> None:+ if not self._started:+ return+ try:+ asyncio.run_coroutine_threadsafe(self._callback(direction, raw, None), self._loop)+ except Exception:+ logger.warning("[history] submit frame failed dir=%s", direction, exc_info=True)++ def stop(self) -> None:+ if not self._started:+ return+ try:+ self._loop.call_soon_threadsafe(self._loop.stop)+ except Exception: # noqa: BLE001+ logger.debug("[history] stop loop failed", exc_info=True)+ if self._thread.is_alive():+ self._thread.join(timeout=5.0)+ self._started = Falsediff --git a/jiuwenswarm/channels/web/history_store/db_actor.py b/jiuwenswarm/channels/web/history_store/db_actor.pynew file mode 100644index 0000000000..c26ae8f699--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/db_actor.py@@ -0,0 +1,246 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 历史 DB-actor:mysql/pg 统一经 foundation 高层 CRUD。++asyncpg/aiomysql engine 绑 event loop;本库被多 loop/线程消费(写经+``HistoryFrameRunner`` 独立 loop、读经同步 HTTP 线程),故 mysql/pg 访问统一在+本 actor 专用 loop 内执行:同步调用 ``run_sync`` 阻塞等结果;async 调用+``run_async`` 投递并 await future。foundation CRUD 始终在 actor loop 内,不跨 loop。++仅企业版远程路径加载(``store._get_actor`` 惰性 import);个人版纯内存不加载本模块,+故不引入 foundation 依赖。+"""++from __future__ import annotations++import asyncio+import logging+import threading+from typing import Any, Awaitable++logger = logging.getLogger("jiuwenswarm.web.history")+++def _row_to_dict(row: Any) -> dict[str, Any]:+ """将 DB 行转 dict;兼容 dict / SQLAlchemy Row / ORM 实体。"""+ if isinstance(row, dict):+ return dict(row)+ if hasattr(row, "keys") and callable(getattr(row, "keys")) and not hasattr(row, "__table__"):+ return {k: row[k] for k in row.keys()}+ return {k: v for k, v in vars(row).items() if not k.startswith("_sa_")}+++class HistoryDbActor:+ """mysql/pg 统一 DB-actor(专用 loop + 守护线程)。"""++ def __init__(self, settings: Any, db_type: str) -> None:+ self._settings = settings+ self._db_type = (db_type or "").strip().lower()+ self._loop: Any = None+ self._thread: threading.Thread | None = None+ self._started: bool = False+ self._handler: Any = None+ self._init_lock = threading.Lock()++ def ensure_started(self) -> None:+ if self._started:+ return+ with self._init_lock:+ if self._started:+ return+ self._loop = asyncio.new_event_loop()+ self._thread = threading.Thread(+ target=self._run_loop, name="web-history-db", daemon=True+ )+ self._thread.start()+ self._started = True++ def _run_loop(self) -> None:+ asyncio.set_event_loop(self._loop)+ self._loop.run_forever()++ def run_sync(self, coro: Awaitable[Any], *, timeout: float = 30.0) -> Any:+ """同步上下文:把 coro 投到 actor loop 执行并阻塞等结果。"""+ self.ensure_started()+ fut = asyncio.run_coroutine_threadsafe(coro, self._loop)+ return fut.result(timeout=timeout)++ async def run_async(self, coro: Awaitable[Any]) -> Any:+ """async 上下文(来自其他 loop):投递到 actor loop 并 await future。"""+ self.ensure_started()+ fut = asyncio.run_coroutine_threadsafe(coro, self._loop)+ return await asyncio.wrap_future(fut)++ async def _get_handler(self) -> Any:+ """构造/复用 foundation handler(mysql→MySQLHandler;pg→PostgreSQLHandler(schema))。++ 在 actor loop 内调用。+ """+ if self._handler is not None:+ return self._handler+ if self._settings is None:+ raise RuntimeError("Web 历史库远程 settings 未配置,无法建立连接")+ from openjiuwen_runtime.foundation.db import MySQLHandler, PostgreSQLHandler+ from .tables import init_web_history_tables++ if self._db_type == "postgresql":+ handler = PostgreSQLHandler(+ host=self._settings.host,+ port=int(self._settings.port),+ database=self._settings.database,+ schema=self._settings.pg_schema,+ user=self._settings.user,+ password=self._settings.password,+ )+ else:+ handler = MySQLHandler(+ host=self._settings.host,+ port=int(self._settings.port),+ database=self._settings.database,+ user=self._settings.user,+ password=self._settings.password,+ )+ await handler.init_database()+ await handler.connect()+ await init_web_history_tables(handler)+ self._handler = handler+ logger.info(+ "[history] %s store 初始化完成 %s:%s/%s%s",+ self._db_type.upper(),+ self._settings.host, self._settings.port, self._settings.database,+ f" schema={self._settings.pg_schema}" if self._db_type == "postgresql" else "",+ )+ return handler++ async def _record_message(+ self,+ *,+ session_id: str,+ request_id: str,+ role: str,+ content: str,+ event_type: str | None,+ ts: float,+ user: str | None,+ title: str | None,+ preview: str,+ ) -> bool:+ handler = await self._get_handler()+ # message insert-ignore:唯一键 (session_id, request_id, role) 冲突则视为未插入+ if await handler.get(+ "messages",+ {"session_id": session_id, "request_id": request_id, "role": role},+ ) is not None:+ return False+ try:+ await handler.create(+ "messages",+ {+ "session_id": session_id,+ "request_id": request_id,+ "role": role,+ "content": content,+ "event_type": event_type,+ "timestamp": ts,+ },+ )+ except Exception as exc: # noqa: BLE001+ low = str(exc).lower()+ if "unique" in low or "duplicate" in low or "conflict" in low:+ return False+ raise+ # upsert session(count+1,title COALESCE 保留已有非空值)+ sess = await handler.get("sessions", {"session_id": session_id})+ if sess is not None:+ d = _row_to_dict(sess)+ new_count = int(d.get("message_count") or 0) + 1+ new_title = d.get("title") or title+ await handler.update(+ "sessions",+ {"session_id": session_id},+ {+ "message_count": new_count,+ "last_preview": preview,+ "updated_at": ts,+ "title": new_title,+ },+ )+ else:+ await handler.create(+ "sessions",+ {+ "session_id": session_id,+ "user": user or "guest",+ "title": title,+ "message_count": 1,+ "last_preview": preview,+ "created_at": ts,+ "updated_at": ts,+ },+ )+ return True++ async def _list_sessions(+ self, *, limit: int, offset: int, user: str,+ ) -> list[dict[str, Any]]:+ if not user:+ user = "guest"+ handler = await self._get_handler()+ rows = await handler.list_records(+ "sessions", {"user": user}, limit=limit, offset=offset, order_by="-updated_at"+ )+ return [_row_to_dict(r) for r in rows]++ async def _get_session_detail(+ self, session_id: str, *, user: str,+ ) -> dict[str, Any] | None:+ if not user:+ user = "guest"+ handler = await self._get_handler()+ s = await handler.get("sessions", {"session_id": session_id, "user": user})+ if s is None:+ return None+ msgs = await handler.list_records(+ "messages", {"session_id": session_id}, limit=10_000, offset=0, order_by="timestamp"+ )+ return {**_row_to_dict(s), "messages": [_row_to_dict(m) for m in msgs]}++ async def record_message(self, **kw: Any) -> bool:+ return await self.run_async(self._record_message(**kw))++ def record_message_sync(self, **kw: Any) -> bool:+ return self.run_sync(self._record_message(**kw))++ async def list_sessions(self, **kw: Any) -> list[dict[str, Any]]:+ return await self.run_async(self._list_sessions(**kw))++ def list_sessions_sync(self, **kw: Any) -> list[dict[str, Any]]:+ return self.run_sync(self._list_sessions(**kw))++ async def get_session_detail(self, **kw: Any) -> dict[str, Any] | None:+ return await self.run_async(self._get_session_detail(**kw))++ def get_session_detail_sync(self, **kw: Any) -> dict[str, Any] | None:+ return self.run_sync(self._get_session_detail(**kw))++ def stop(self) -> None:+ if not self._started:+ return+ try:+ if self._handler is not None and self._loop is not None:+ asyncio.run_coroutine_threadsafe(+ self._handler.disconnect(), self._loop+ ).result(timeout=10)+ except Exception: # noqa: BLE001+ logger.debug("[history] db handler disconnect failed", exc_info=True)+ self._handler = None+ try:+ if self._loop is not None:+ self._loop.call_soon_threadsafe(self._loop.stop)+ except Exception: # noqa: BLE001+ pass+ if self._thread is not None and self._thread.is_alive():+ self._thread.join(timeout=5)+ self._started = False+ self._loop = None+ self._thread = Nonediff --git a/jiuwenswarm/channels/web/history_store/settings.py b/jiuwenswarm/channels/web/history_store/settings.pynew file mode 100644index 0000000000..56d26fc075--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/settings.py@@ -0,0 +1,78 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 会话历史库:配置与类型解析(个人版纯内存;企业版 mysql/pg)。++本模块不 import foundation,个人版加载安全。+"""++from __future__ import annotations++import os+from dataclasses import dataclass++_DEFAULT_DB_NAME = "web"+++def _env(*names: str, default: str = "") -> str:+ for name in names:+ raw = os.getenv(name)+ if raw is not None and str(raw).strip():+ return str(raw).strip()+ return default+++def resolve_history_db_type() -> str:+ """解析 Web 会话历史库类型。++ 优先级:``WEB_DB_TYPE`` → ``DB_TYPE`` → 已配 ``WEB_DB_HOST`` 则 ``mysql`` →+ 按 ``DEPLOYMENT_MODE``(企业 active-standby/distributed ``mysql``,standalone ``memory``)。++ sqlite 已废弃:两端均不支持(个人版纯内存、企业版仅 mysql/pg)。+ 若显式配置 ``sqlite``,由 ``ChatHistoryStore.for_db_type`` 回退内存并告警。+ """+ explicit = _env("WEB_DB_TYPE") or _env("DB_TYPE")+ if explicit:+ return explicit.strip().lower()+ if _env("WEB_DB_HOST"):+ return "mysql"+ try:+ from jiuwenswarm.deployment_mode import (+ history_storage_backend,+ normalize_deployment_mode,+ )++ mode = normalize_deployment_mode(os.getenv("DEPLOYMENT_MODE", "standalone"))+ return history_storage_backend(mode)+ except Exception:+ return "memory"+++@dataclass(frozen=True)+class WebHistoryDbSettings:+ """Web 历史库远程连接(MySQL / PostgreSQL,独立 database ``web``)。"""++ host: str+ port: int+ user: str+ password: str+ database: str = _DEFAULT_DB_NAME+ pg_schema: str = "public"++ @classmethod+ def from_env(cls) -> "WebHistoryDbSettings | None":+ host = _env("WEB_DB_HOST")+ if not host:+ return None+ port_raw = _env("WEB_DB_PORT", default="3306")+ try:+ port = int(port_raw)+ except ValueError:+ port = 3306+ return cls(+ host=host,+ port=port,+ user=_env("WEB_DB_USER", default="root"),+ password=_env("WEB_DB_PASSWORD"),+ database=_env("WEB_DB_NAME", default=_DEFAULT_DB_NAME) or _DEFAULT_DB_NAME,+ pg_schema=_env("WEB_PG_SCHEMA", default="public") or "public",+ )diff --git a/jiuwenswarm/channels/web/history_store/store.py b/jiuwenswarm/channels/web/history_store/store.pynew file mode 100644index 0000000000..b30daf18d8--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/store.py@@ -0,0 +1,314 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""会话历史存储:个人版纯内存;企业版 mysql/pg 经 foundation DB-actor。++写路径可来自:+- ``app_web`` WS 反代(``HistoryFrameRunner``)+- Gateway ``WebChannel`` Listen++存储后端:+- ``memory``(个人版):进程内内存,不落库、不引 foundation。+- ``mysql``/``postgresql``(企业版):经 foundation 高层 CRUD+ (``list_records``/``get``/``create``/``update``),统一在 ``HistoryDbActor`` 专用 loop+ 内执行(asyncpg/aiomysql engine 绑 event loop,而本库被多 loop/线程消费——写经+ ``HistoryFrameRunner`` 独立 loop、读经同步 HTTP 线程)。++sqlite 已废弃(两端均不支持)。+"""++from __future__ import annotations++import asyncio+import logging+import threading+from typing import Any, Literal++from .settings import WebHistoryDbSettings, resolve_history_db_type++logger = logging.getLogger("jiuwenswarm.web.history")++_TITLE_LEN = 30+_PREVIEW_LEN = 100+_MAX_LIST_LIMIT = 100++HistoryBackend = Literal["memory", "mysql", "postgresql"]+++class ChatHistoryStore:+ """会话历史存储:memory(个人版)/ mysql·pg(企业版)。"""++ def __init__(+ self,+ settings: WebHistoryDbSettings | None = None,+ *,+ memory: bool = False,+ db_type: str | None = None,+ ) -> None:+ self._settings = settings+ self._memory = memory+ self._db_type = (db_type or "").strip().lower() or None+ self._mem_lock = threading.Lock()+ self._mem_sessions: dict[str, dict[str, Any]] = {}+ self._mem_messages: list[dict[str, Any]] = []+ self._actor: Any = None # HistoryDbActor(惰性,仅企业版远程路径)++ @classmethod+ def for_db_type(cls, db_type: str) -> "ChatHistoryStore":+ normalized = str(db_type or "").strip().lower() or "memory"+ if normalized == "memory":+ return cls(memory=True)+ if normalized in ("postgresql", "postgres", "pg"):+ return cls(settings=WebHistoryDbSettings.from_env(), db_type="postgresql")+ if normalized == "mysql":+ return cls(settings=WebHistoryDbSettings.from_env(), db_type="mysql")+ logger.warning(+ "[history] 不支持的历史库类型 %r,回退内存(不支持 sqlite)",+ normalized,+ )+ return cls(memory=True)++ @classmethod+ def from_env(cls) -> "ChatHistoryStore":+ return cls.for_db_type(resolve_history_db_type())++ @classmethod+ def memory(cls) -> "ChatHistoryStore":+ return cls(memory=True)++ @property+ def backend(self) -> HistoryBackend:+ if self._memory:+ return "memory"+ if self._db_type == "postgresql":+ return "postgresql"+ if self._db_type == "mysql":+ return "mysql"+ return "memory"++ @property+ def mysql_settings(self) -> WebHistoryDbSettings | None:+ return self._settings++ @property+ def available(self) -> bool:+ if self._memory:+ return True+ return self._settings is not None++ def _get_actor(self) -> Any:+ if self._actor is None:+ from .db_actor import HistoryDbActor++ self._actor = HistoryDbActor(self._settings, self._db_type)+ return self._actor++ def _insert_message_and_upsert_session(+ self,+ _conn: Any,+ *,+ session_id: str,+ request_id: str,+ role: str,+ content: str,+ event_type: str | None,+ ts: float,+ user: str | None,+ title: str | None,+ preview: str,+ ) -> bool:+ """memory 写入(企业版远程走 actor,不经此方法)。"""+ key = (session_id, request_id, role)+ with self._mem_lock:+ if any(+ (m["session_id"], m["request_id"], m["role"]) == key+ for m in self._mem_messages+ ):+ return False+ self._mem_messages.append({+ "session_id": session_id,+ "request_id": request_id,+ "role": role,+ "content": content,+ "event_type": event_type,+ "timestamp": ts,+ })+ existing = self._mem_sessions.get(session_id)+ if existing is None:+ self._mem_sessions[session_id] = {+ "session_id": session_id,+ "user": user or "guest",+ "title": title,+ "message_count": 1,+ "last_preview": preview,+ "created_at": ts,+ "updated_at": ts,+ }+ else:+ existing["message_count"] = int(existing.get("message_count") or 0) + 1+ existing["last_preview"] = preview+ existing["updated_at"] = ts+ if not existing.get("title") and title:+ existing["title"] = title+ return True++ async def record_user(+ self,+ *,+ request_id: str,+ session_id: str,+ query: str,+ ts: float,+ user: str | None = None,+ ) -> bool:+ if not user:+ user = "guest"+ title = query[:_TITLE_LEN]+ preview = query[:_PREVIEW_LEN]+ if self._memory:+ inserted = await asyncio.to_thread(+ self._insert_message_and_upsert_session,+ None,+ session_id=session_id,+ request_id=request_id,+ role="user",+ content=query,+ event_type=None,+ ts=ts,+ user=user,+ title=title,+ preview=preview,+ )+ else:+ inserted = await self._get_actor().record_message(+ session_id=session_id,+ request_id=request_id,+ role="user",+ content=query,+ event_type=None,+ ts=ts,+ user=user,+ title=title,+ preview=preview,+ )+ if inserted:+ logger.info(+ "[history] 落盘 user: rid=%s sid=%s user=%s len=%d",+ request_id, session_id, user, len(query),+ )+ return inserted++ async def record_assistant(+ self,+ *,+ request_id: str,+ session_id: str,+ content: str,+ event_type: str,+ ts: float,+ ) -> bool:+ preview = content[:_PREVIEW_LEN]+ if self._memory:+ inserted = await asyncio.to_thread(+ self._insert_message_and_upsert_session,+ None,+ session_id=session_id,+ request_id=request_id,+ role="assistant",+ content=content,+ event_type=event_type,+ ts=ts,+ user="guest",+ title=None,+ preview=preview,+ )+ else:+ inserted = await self._get_actor().record_message(+ session_id=session_id,+ request_id=request_id,+ role="assistant",+ content=content,+ event_type=event_type,+ ts=ts,+ user="guest",+ title=None,+ preview=preview,+ )+ if inserted:+ logger.info(+ "[history] 落盘 assistant: rid=%s sid=%s event=%s len=%d",+ request_id, session_id, event_type, len(content),+ )+ return inserted++ def list_sessions_blocking(+ self, *, limit: int, offset: int, user: str | None,+ ) -> list[dict[str, Any]]:+ limit = max(1, min(limit, _MAX_LIST_LIMIT))+ offset = max(0, offset)+ if not user:+ user = "guest"+ if self._memory:+ with self._mem_lock:+ rows = [+ dict(s) for s in self._mem_sessions.values()+ if s.get("user") == user+ ]+ rows.sort(key=lambda r: float(r.get("updated_at") or 0), reverse=True)+ return rows[offset:offset + limit]+ try:+ return self._get_actor().list_sessions_sync(+ limit=limit, offset=offset, user=user,+ )+ except Exception:+ logger.exception("[history] %s 读取会话列表失败", self.backend.upper())+ return []++ def get_session_detail_blocking(+ self, session_id: str, *, user: str | None,+ ) -> dict[str, Any] | None:+ if not user:+ user = "guest"+ if self._memory:+ with self._mem_lock:+ s = self._mem_sessions.get(session_id)+ if s is None or s.get("user") != user:+ return None+ msgs = [+ {+ "role": m["role"],+ "content": m["content"],+ "event_type": m["event_type"],+ "timestamp": m["timestamp"],+ "request_id": m["request_id"],+ }+ for m in self._mem_messages+ if m["session_id"] == session_id+ ]+ msgs.sort(key=lambda m: float(m.get("timestamp") or 0))+ return {**s, "messages": msgs}+ try:+ return self._get_actor().get_session_detail_sync(session_id, user=user)+ except Exception:+ logger.exception("[history] %s 读取会话详情失败", self.backend.upper())+ return None++ async def list_sessions(+ self, *, limit: int = 20, offset: int = 0,+ ) -> list[dict[str, Any]]:+ if self._memory:+ return await asyncio.to_thread(+ self.list_sessions_blocking, limit=limit, offset=offset, user=None,+ )+ return await self._get_actor().list_sessions(limit=limit, offset=offset, user=None)++ async def get_session_detail(self, session_id: str) -> dict[str, Any] | None:+ if self._memory:+ return await asyncio.to_thread(+ self.get_session_detail_blocking, session_id, user=None,+ )+ return await self._get_actor().get_session_detail(session_id, user=None)++ async def close(self) -> None:+ if self._actor is not None:+ self._actor.stop()+ logger.info("[history] store 已关闭 backend=%s", self.backend)diff --git a/jiuwenswarm/channels/web/history_store/tables.py b/jiuwenswarm/channels/web/history_store/tables.pynew file mode 100644index 0000000000..4d5707ad91--- /dev/null+++ b/jiuwenswarm/channels/web/history_store/tables.py@@ -0,0 +1,62 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved++"""Web 会话历史表定义(sessions / messages)。++供 mysql/pg 经 foundation handler ``init_table`` 注册 ORM model,使高层 CRUD+(``list_records`` / ``get`` / ``create`` / ``update``) 可用。++仅在 Web 历史库走 mysql/pg(企业版)时由 ``db_actor`` 惰性 import;+个人版(纯内存)不会加载本模块,故不引入 foundation 依赖。+"""++from __future__ import annotations++from openjiuwen_runtime.foundation.db.table_def import (+ ColumnDefinition,+ IndexDefinition,+ TableDefinition,+)++# 时间戳列用 float(DOUBLE / REAL epoch 秒),与现有数据模型一致。+# content 用 mediumtext:mysql → MEDIUMTEXT(16MB),pg → TEXT(无界)。++SESSIONS_TABLE_DEF = TableDefinition(+ table_name="sessions",+ columns=[+ ColumnDefinition("session_id", "string", primary_key=True, nullable=False),+ ColumnDefinition("user", "string", nullable=False, default="guest"),+ ColumnDefinition("title", "string", nullable=True),+ ColumnDefinition("message_count", "integer", nullable=False, default=0),+ ColumnDefinition("last_preview", "string", nullable=True),+ ColumnDefinition("created_at", "float", nullable=False),+ ColumnDefinition("updated_at", "float", nullable=False),+ ],+ indexes=[+ IndexDefinition(["user", "updated_at"], unique=False),+ ],+)++MESSAGES_TABLE_DEF = TableDefinition(+ table_name="messages",+ columns=[+ ColumnDefinition("id", "integer", primary_key=True, nullable=False, autoincrement=True),+ ColumnDefinition("session_id", "string", nullable=False),+ ColumnDefinition("request_id", "string", nullable=False),+ ColumnDefinition("role", "string", nullable=False),+ ColumnDefinition("content", "mediumtext", nullable=False),+ ColumnDefinition("event_type", "string", nullable=True),+ ColumnDefinition("timestamp", "float", nullable=False),+ ],+ indexes=[+ IndexDefinition(["session_id", "request_id", "role"], unique=True),+ IndexDefinition(["session_id", "timestamp"], unique=False),+ ],+)++ALL_TABLE_DEFINITIONS = (SESSIONS_TABLE_DEF, MESSAGES_TABLE_DEF)+++async def init_web_history_tables(handler) -> None:+ """在已连接的 handler 上注册 Web 历史表(幂等:表已存在则跳过创建)。"""+ for table_def in ALL_TABLE_DEFINITIONS:+ await handler.init_table(table_def)diff --git a/jiuwenswarm/deployment_mode.py b/jiuwenswarm/deployment_mode.pyindex b919cb4f55..c9e6f7e7b7 100644--- a/jiuwenswarm/deployment_mode.py+++ b/jiuwenswarm/deployment_mode.py@@ -26,7 +26,7 @@ VALID_DEPLOYMENT_MODES: tuple[str, ...] = ()SessionStorageBackend = Literal["local", "redis"]-HistoryStorageBackend = Literal["sqlite", "mysql"]+HistoryStorageBackend = Literal["memory", "mysql"]def normalize_deployment_mode(raw: object) -> str:@@ -57,15 +57,16 @@ def session_storage_backend(mode: str) -> SessionStorageBackend:def history_storage_backend(mode: str) -> HistoryStorageBackend:"""Web 会话历史默认存储后端。- - standalone:本地 SQLite(可无 MySQL)+ - standalone:纯内存(个人版不落库;web 数据库为企业版特性)- active-standby / distributed:MySQL 独立库 ``web``(删 Pod 不丢历史)实际运行时仍以 ``WEB_DB_TYPE`` / ``WEB_DB_HOST`` 等环境变量优先(见 ``resolve_history_db_type``);本函数表达「部署模式推荐默认值」。+ sqlite 已废弃(两端均不支持)。"""if normalize_deployment_mode(mode) in (MODE_ACTIVE_STANDBY, MODE_DISTRIBUTED):return "mysql"- return "sqlite"+ return "memory"def default_cron_enabled(mode: str) -> bool:diff --git a/jiuwenswarm/extensions/redis/redis_runtime.py b/jiuwenswarm/extensions/redis/redis_runtime.pyindex 0844747ee6..a1eb616b55 100644--- a/jiuwenswarm/extensions/redis/redis_runtime.py+++ b/jiuwenswarm/extensions/redis/redis_runtime.py@@ -144,24 +144,27 @@ async def init_gateway_redis_from_config(full_cfg: dict[str, Any] | None) -> Nongw = cfg_in.get("gateway")gw = gw if isinstance(gw, dict) else {}declared = str(gw.get("deployment_mode") or "standalone").strip().lower()- _declared_deployment_mode = declared if declared in ("standalone", "active-standby") else "standalone"+ _declared_deployment_mode = declared if declared in ("standalone", "active-standby", "distributed") else "standalone"iid = str(gw.get("instance_id") or "").strip()- if _declared_deployment_mode == "active-standby":+ # active-standby / distributed 都需要 instance_id 标识(主备选主 / 多副本区分)+ if _declared_deployment_mode in ("active-standby", "distributed"):_gateway_instance_id = iid or uuid.uuid4().hexif not iid:logger.info("[GatewayRedis] gateway.instance_id unset; generated %s", _gateway_instance_id)else:_gateway_instance_id = iid if iid else None- if _declared_deployment_mode != "active-standby":+ # 仅 standalone 跳过 Redis init;active-standby / distributed 都需要连 Redis+ if _declared_deployment_mode == "standalone":logger.debug("[GatewayRedis] deployment_mode=standalone; skip Redis init (§3.3.4)")return# 企业版特性:仅企业版开启时启用主备 Redisif not is_enterprise():logger.debug(- "[GatewayRedis] deployment_mode=active-standby but not enterprise edition; skip Redis init"+ "[GatewayRedis] deployment_mode=%s but not enterprise edition; skip Redis init",+ _declared_deployment_mode,)returndiff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex f12b52f426..a33950a2a1 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -74,9 +74,9 @@ logger = logging.getLogger("jiuwenswarm.gateway")def _uses_external_agent_config() -> bool:"""企业版或外置 Runtime 托管:配置经 Manager→ConfigReceiver→runtime_notify,不经 Gateway push。"""- from jiuwenswarm.gateway.edition import is_gateway_enterprise+ from jiuwenswarm.common.utils import is_enterprise- if is_gateway_enterprise():+ if is_enterprise():return Truereturn bool(os.getenv("GATEWAY_RUNTIME_MANAGER_URL", "").strip())@@ -1682,13 +1682,13 @@ async def _run_with_telemetry(gateway_storage_ctx = Nonetry:- from jiuwenswarm.gateway.edition import EDITION_ENTERPRISE, resolve_gateway_edition+ from jiuwenswarm.common.utils import is_enterprisefrom jiuwenswarm.gateway.storage_assembly.setup import (ensure_enterprise_storage_context,wire_enterprise_manager_ws_store_async,)- if resolve_gateway_edition(full_cfg) == EDITION_ENTERPRISE:+ if is_enterprise():gateway_storage_ctx = ensure_enterprise_storage_context(full_cfg,existing=gateway_storage_ctx,diff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.pyindex 7a93dddfa5..2c5f209f16 100644--- a/jiuwenswarm/gateway/channel_manager/web/invoke.py+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py@@ -29,9 +29,9 @@ _ENTERPRISE_SKILL_ALLOWED = frozenset({"skills.list", "skills.get", "skills.entedef is_enterprise_write_forbidden(method: str) -> bool:"""Central guard shared by WS and HTTP; Cron and locale remain user-writable."""- from jiuwenswarm.gateway.edition import is_gateway_enterprise+ from jiuwenswarm.common.utils import is_enterprise- if not is_gateway_enterprise():+ if not is_enterprise():return Falseif method in _ENTERPRISE_BLOCKED_EXACT or method.startswith(_ENTERPRISE_BLOCKED_PREFIXES):return Truediff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.py b/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.pyindex 7b5243d591..0eb8ac2f92 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.py@@ -51,15 +51,12 @@ def _trust_client_tenant_headers(client_host: str | None) -> bool:if explicit in {"0", "false", "no"}:return False# 企业用户面通过 NodePort/Web Pod 访问时,客户端地址不是回环地址。- # 企业版的身份边界由上游认证和 Gateway edition 控制,必须把选中的+ # 企业版的身份边界由上游认证和 ``is_enterprise()`` 控制,必须把选中的# user/group/bot 透传给 Runtime 路由;个人版继续只信任本机请求。- try:- from jiuwenswarm.gateway.edition import is_gateway_enterprise+ from jiuwenswarm.common.utils import is_enterprise- if is_gateway_enterprise():- return True- except Exception: # noqa: BLE001- logger.debug("failed to resolve gateway edition", exc_info=True)+ if is_enterprise():+ return Truehost = str(client_host or "").strip().lower()return host in {"127.0.0.1", "::1", "localhost"}diff --git a/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.py b/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.pyindex b1caa00dc3..2b189ddb67 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.py@@ -147,16 +147,17 @@ class WebRpcHost:runner = HistoryFrameRunner(store)runner.start()self._history_runner = runner- if store.backend == "mysql" and store.mysql_settings is not None:+ if store.mysql_settings is not None:s = store.mysql_settingslogger.info(- "WebChannel enterprise history capture: mysql %s:%s/%s",- s.host, s.port, s.database,+ "WebChannel enterprise history capture: %s %s:%s/%s%s",+ store.backend, s.host, s.port, s.database,+ f" schema={s.pg_schema}" if store.backend == "postgresql" else "",)else:logger.info(- "WebChannel enterprise history capture: %s db=%s",- store.backend, store.db_path,+ "WebChannel enterprise history capture: %s",+ store.backend,)except Exception:logger.warning("WebChannel 启动会话历史采集失败", exc_info=True)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/__init__.py b/jiuwenswarm/gateway/config/enterprise/tables/__init__.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/__init__.pyrename to jiuwenswarm/gateway/config/enterprise/tables/__init__.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/application_config_models.py b/jiuwenswarm/gateway/config/enterprise/tables/application_config_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/application_config_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/application_config_models.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/config_effective_policy_models.py b/jiuwenswarm/gateway/config/enterprise/tables/config_effective_policy_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/config_effective_policy_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/config_effective_policy_models.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/cron_job_models.py b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.pysimilarity index 90%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/cron_job_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.pyindex ce680b5887..47b75855b0 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/cron_job_models.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py@@ -22,6 +22,8 @@ CRON_JOB_TABLE_DEF = TableDefinition(nullable=False,),ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),+ ColumnDefinition("service_id", "string", length=64, nullable=False, default="default"),+ ColumnDefinition("agent_id", "string", length=64, nullable=False, default="default"),ColumnDefinition("job_id", "string", length=64, nullable=False),ColumnDefinition("group_id", "string", length=256, nullable=True),ColumnDefinition("bot_id", "string", length=256, nullable=True),@@ -45,7 +47,7 @@ CRON_JOB_TABLE_DEF = TableDefinition(ColumnDefinition("data", "json", nullable=True),],indexes=[- IndexDefinition(["jiuwenclaw_id", "job_id"], unique=True),+ IndexDefinition(["jiuwenclaw_id", "service_id", "agent_id", "job_id"], unique=True),# 该索引暂时注释掉:jiuwenclaw_id(64)+group_id(256)+bot_id(256)+user_id(256)# 在 utf8mb4 下共 3328 字节,超过 MySQL 索引键上限 3072 字节。# 缩短 group_id/bot_id/user_id 列长度或改用前缀索引后再启用。diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/instance_resource_models.py b/jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/instance_resource_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/key_models.py b/jiuwenswarm/gateway/config/enterprise/tables/key_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/key_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/key_models.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/session_map_models.py b/jiuwenswarm/gateway/config/enterprise/tables/session_map_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/session_map_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/session_map_models.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.pyrename to jiuwenswarm/gateway/config/enterprise/tables/table_init.pydiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/template_models.py b/jiuwenswarm/gateway/config/enterprise/tables/template_models.pysimilarity index 100%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/template_models.pyrename to jiuwenswarm/gateway/config/enterprise/tables/template_models.pydiff --git a/jiuwenswarm/gateway/edition.py b/jiuwenswarm/gateway/edition.pydeleted file mode 100644index a323fac47c..0000000000--- a/jiuwenswarm/gateway/edition.py+++ /dev/null@@ -1,53 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Gateway 产品形态:个人版 vs 企业版(唯一来源:``config.yaml::gateway.edition``)。"""--from __future__ import annotations--from typing import Any, Literal--GatewayEdition = Literal["personal", "enterprise"]--EDITION_PERSONAL: GatewayEdition = "personal"-EDITION_ENTERPRISE: GatewayEdition = "enterprise"--_VALID_EDITIONS: frozenset[str] = frozenset({EDITION_PERSONAL, EDITION_ENTERPRISE})---def normalize_gateway_edition(raw: object) -> GatewayEdition:- """归一化 ``gateway.edition``;非法/空值回退 ``personal``。"""- edition = str(raw or "").strip().lower()- if edition in _VALID_EDITIONS:- return edition # type: ignore[return-value]- if edition in {"ee", "corp", "enterprise_edition"}:- return EDITION_ENTERPRISE- return EDITION_PERSONAL---def resolve_gateway_edition(cfg: dict[str, Any] | None = None) -> GatewayEdition:- """解析 Gateway 产品形态;仅读 ``gateway.edition``,缺省为 ``personal``。"""- config = cfg- if config is None:- try:- from jiuwenswarm.common.config import get_config-- config = get_config()- except Exception:- config = {}-- gw = config.get("gateway") if isinstance(config, dict) else None- gw = gw if isinstance(gw, dict) else {}- return normalize_gateway_edition(gw.get("edition"))---def is_gateway_enterprise(cfg: dict[str, Any] | None = None) -> bool:- return resolve_gateway_edition(cfg) == EDITION_ENTERPRISE---__all__ = [- "EDITION_ENTERPRISE",- "EDITION_PERSONAL",- "GatewayEdition",- "is_gateway_enterprise",- "normalize_gateway_edition",- "resolve_gateway_edition",-]diff --git a/jiuwenswarm/gateway/routing/session_map_access.py b/jiuwenswarm/gateway/routing/session_map_access.pyindex 3a03d77d87..bf1fc9737a 100644--- a/jiuwenswarm/gateway/routing/session_map_access.py+++ b/jiuwenswarm/gateway/routing/session_map_access.py@@ -19,9 +19,9 @@ _repo: SessionMapRepository | None = Nonedef session_map_read_through_enabled(cfg: dict[str, Any] | None = None) -> bool:"""Enterprise / multi-replica need read-through; personal single-node keeps local cache."""- from jiuwenswarm.gateway.edition import EDITION_ENTERPRISE, resolve_gateway_edition+ from jiuwenswarm.common.utils import is_enterprise- if resolve_gateway_edition(cfg) == EDITION_ENTERPRISE:+ if is_enterprise():return Truetry:replicas = int(os.getenv("GATEWAY_REPLICAS", "1") or "1")diff --git a/jiuwenswarm/gateway/storage_assembly/db_connection.py b/jiuwenswarm/gateway/storage_assembly/db_connection.pyindex f717b27adf..57cda54468 100644--- a/jiuwenswarm/gateway/storage_assembly/db_connection.py+++ b/jiuwenswarm/gateway/storage_assembly/db_connection.py@@ -9,8 +9,6 @@ from typing import Anyfrom jiuwenswarm.gateway.storage.errors import StorageUnavailableError-_SQLITE_TYPES = frozenset({"sqlite", "aiosqlite"})-def resolve_gateway_replicas() -> int:"""解析 ``GATEWAY_REPLICAS``;缺省为 1。"""@@ -34,9 +32,11 @@ def resolve_gateway_db_type() -> str:def assert_replicas_db_compat() -> None:"""``GATEWAY_REPLICAS > 1`` 时禁止 sqlite。"""+ from openjiuwen_runtime.foundation.db.utils import is_sqlite+replicas = resolve_gateway_replicas()db_type = resolve_gateway_db_type()- if replicas > 1 and db_type in _SQLITE_TYPES:+ if replicas > 1 and is_sqlite(db_type):raise StorageUnavailableError(f"GATEWAY_REPLICAS={replicas} forbids sqlite; ""set GATEWAY_DB_TYPE to mysql or postgresql"diff --git a/jiuwenswarm/gateway/storage_assembly/setup.py b/jiuwenswarm/gateway/storage_assembly/setup.pyindex 1aa2eb6ccb..5cf8896338 100644--- a/jiuwenswarm/gateway/storage_assembly/setup.py+++ b/jiuwenswarm/gateway/storage_assembly/setup.py@@ -1,5 +1,5 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""按 ``gateway.edition`` 装配 StorageContext。"""+"""按 ``is_enterprise()`` 装配 StorageContext(个人版/企业版)。"""from __future__ import annotations@@ -8,11 +8,7 @@ import osfrom pathlib import Pathfrom typing import Any-from jiuwenswarm.gateway.edition import (- EDITION_ENTERPRISE,- EDITION_PERSONAL,- resolve_gateway_edition,-)+from jiuwenswarm.common.utils import is_enterprisefrom jiuwenswarm.gateway.storage.backends.db.persistent_store import DbPersistentBackendfrom jiuwenswarm.gateway.storage.backends.file_persistent import FilePersistentBackendfrom jiuwenswarm.gateway.storage.backends.memory_ephemeral import MemoryEphemeralBackend@@ -48,8 +44,8 @@ def _redis_client() -> Any | None:return client-def _create_persistent(edition: str) -> PersistentStore:- if edition == "enterprise":+def _create_persistent() -> PersistentStore:+ if is_enterprise():from jiuwenswarm.gateway.storage_assembly.db_connection import GatewayDbConnectionassert_replicas_db_compat()@@ -88,8 +84,8 @@ def _require_redis_client() -> Any:return client-def _create_ephemeral_factory(edition: str):- if edition != "enterprise":+def _create_ephemeral_factory():+ if not is_enterprise():def memory_factory(namespace: str) -> EphemeralStore:return MemoryEphemeralBackend(namespace)@@ -212,30 +208,21 @@ def _wire_personal_yaml_section_repositories(set_preferred_language_config_repository,)- if resolve_gateway_edition(cfg) != EDITION_PERSONAL:+ if is_enterprise():return- edition = EDITION_PERSONALinstance_id = resolve_storage_instance_id(cfg)set_heartbeat_config_repository(- create_heartbeat_config_repository(- store, edition, instance_id=instance_id- )+ create_heartbeat_config_repository(store, instance_id=instance_id))set_browser_config_repository(- create_browser_config_repository(- store, edition, instance_id=instance_id- )+ create_browser_config_repository(store, instance_id=instance_id))set_preferred_language_config_repository(- create_preferred_language_config_repository(- store, edition, instance_id=instance_id- )+ create_preferred_language_config_repository(store, instance_id=instance_id))set_a2ui_config_repository(- create_a2ui_config_repository(- store, edition, instance_id=instance_id- )+ create_a2ui_config_repository(store, instance_id=instance_id))@@ -253,27 +240,18 @@ def _wire_config_and_cron_repositories(from jiuwenswarm.gateway.cron.job_access import set_cron_persistent_storefrom jiuwenswarm.gateway.storage.access import set_persistent_store- edition = resolve_gateway_edition(cfg)instance_id = resolve_storage_instance_id(cfg)set_channel_config_repository(- create_channel_config_repository(- store, edition, instance_id=instance_id- )+ create_channel_config_repository(store, instance_id=instance_id))set_permissions_config_repository(- create_permissions_config_repository(- store, edition, instance_id=instance_id- )+ create_permissions_config_repository(store, instance_id=instance_id))set_logging_config_repository(- create_logging_config_repository(- store, edition, instance_id=instance_id- )+ create_logging_config_repository(store, instance_id=instance_id))set_memory_config_repository(- create_memory_config_repository(- store, edition, instance_id=instance_id- )+ create_memory_config_repository(store, instance_id=instance_id))set_persistent_store(store)set_cron_persistent_store(store)@@ -348,7 +326,7 @@ async def setup_gateway_storage_repositories(if repos_on:_wire_config_and_cron_repositories(store, cfg)- if resolve_gateway_edition(cfg) == EDITION_ENTERPRISE:+ if is_enterprise():from jiuwenswarm.gateway.config.enterprise.access import (set_enterprise_record_repositories,)@@ -395,7 +373,7 @@ def ensure_enterprise_storage_context(from jiuwenswarm.common.config import get_configcfg = get_config()- if resolve_gateway_edition(cfg) != EDITION_ENTERPRISE:+ if not is_enterprise():raise ValueError("ensure_enterprise_storage_context requires enterprise edition")return create_gateway_storage_context(cfg)@@ -419,7 +397,7 @@ async def wire_enterprise_manager_ws_store_async(from jiuwenswarm.common.config import get_configcfg = get_config()- if resolve_gateway_edition(cfg) != EDITION_ENTERPRISE:+ if not is_enterprise():returnfrom jiuwenswarm.gateway.storage_assembly.manager_ws_bridge import (wire_manager_ws_table_store,@@ -482,9 +460,9 @@ async def teardown_session_map_repository(ctx: StorageContext) -> None:def create_gateway_storage_context(cfg: dict[str, Any] | None = None) -> StorageContext:- """按 ``gateway.edition`` 组装进程级 ``StorageContext``(持久化 + 临时态入口)。+ """按 ``is_enterprise()`` 组装进程级 ``StorageContext``(持久化 + 临时态入口)。- - 解析 edition(``personal`` / ``enterprise``)+ - 企业版/个人版由 ``is_enterprise()`` 判定- 选择 Persistent backend:personal → 文件;enterprise → DB- 选择 Ephemeral 工厂:personal → 内存;enterprise → Redis@@ -495,27 +473,25 @@ def create_gateway_storage_context(cfg: dict[str, Any] | None = None) -> Storagefrom jiuwenswarm.common.config import get_configcfg = get_config()- edition = resolve_gateway_edition(cfg)return StorageContext(- _create_persistent(edition),- ephemeral_factory=_create_ephemeral_factory(edition),+ _create_persistent(),+ ephemeral_factory=_create_ephemeral_factory(),)def create_channel_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):- """按 edition 选 Codec,业务侧拿到的是同一个 Repository。"""+ """按 ``is_enterprise()`` 选 Codec,业务侧拿到的是同一个 Repository。"""from jiuwenswarm.gateway.config.channel import (ChannelConfigRepository,DbRowChannelCodec,YamlMapChannelCodec,)- if edition == EDITION_ENTERPRISE:+ if is_enterprise():codec = DbRowChannelCodec(instance_id=instance_id)else:codec = YamlMapChannelCodec()@@ -530,7 +506,6 @@ def create_session_map_repository(store: PersistentStore):def create_permissions_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -542,7 +517,7 @@ def create_permissions_config_repository(codec = (DbBodySectionCodec()- if edition == EDITION_ENTERPRISE+ if is_enterprise()else YamlSectionCodec())return PermissionsConfigRepository(@@ -552,7 +527,6 @@ def create_permissions_config_repository(def create_logging_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -564,7 +538,7 @@ def create_logging_config_repository(codec = (db_logging_codec()- if edition == EDITION_ENTERPRISE+ if is_enterprise()else YamlSectionCodec())return LoggingConfigRepository(store, codec, instance_id=instance_id)@@ -572,7 +546,6 @@ def create_logging_config_repository(def create_memory_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -584,15 +557,15 @@ def create_memory_config_repository(codec = (DbBodySectionCodec()- if edition == EDITION_ENTERPRISE+ if is_enterprise()else YamlSectionCodec())return MemoryConfigRepository(store, codec, instance_id=instance_id)-def _require_personal_config_store(edition: str, store_name: str) -> None:+def _require_personal_config_store(store_name: str) -> None:"""heartbeat / browser / preferred_language / a2ui 无企业同构表。"""- if edition == EDITION_ENTERPRISE:+ if is_enterprise():raise ValueError(f"{store_name} is personal-only (YAML overlay); ""no enterprise DB table"@@ -601,7 +574,6 @@ def _require_personal_config_store(edition: str, store_name: str) -> None:def create_heartbeat_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -610,7 +582,7 @@ def create_heartbeat_config_repository(YamlSectionCodec,)- _require_personal_config_store(edition, "heartbeat_config")+ _require_personal_config_store("heartbeat_config")return HeartbeatConfigRepository(store, YamlSectionCodec(), instance_id=instance_id)@@ -618,7 +590,6 @@ def create_heartbeat_config_repository(def create_browser_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -627,7 +598,7 @@ def create_browser_config_repository(YamlSectionCodec,)- _require_personal_config_store(edition, "browser_config")+ _require_personal_config_store("browser_config")return BrowserConfigRepository(store, YamlSectionCodec(), instance_id=instance_id)@@ -635,7 +606,6 @@ def create_browser_config_repository(def create_preferred_language_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -644,7 +614,7 @@ def create_preferred_language_config_repository(YamlSectionCodec,)- _require_personal_config_store(edition, "preferred_language_config")+ _require_personal_config_store("preferred_language_config")return PreferredLanguageConfigRepository(store, YamlSectionCodec(), instance_id=instance_id)@@ -652,7 +622,6 @@ def create_preferred_language_config_repository(def create_a2ui_config_repository(store: PersistentStore,- edition: str,*,instance_id: str = "",):@@ -661,7 +630,7 @@ def create_a2ui_config_repository(YamlSectionCodec,)- _require_personal_config_store(edition, "a2ui_config")+ _require_personal_config_store("a2ui_config")return A2uiConfigRepository(store, YamlSectionCodec(), instance_id=instance_id)diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex aa467b04b4..c4194131e5 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -280,17 +280,6 @@ async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> Noneexcept Exception: # noqa: BLE001logger.warning("[AgentServer] log_masking_rule cold load skipped", exc_info=True)- if is_enterprise():- try:- from jiuwenswarm.agents.harness.common.memory.config import (- reload_embed_config_from_gateway_db,- )-- await reload_embed_config_from_gateway_db()- logger.info("[AgentServer] embed_config loaded from Gateway DB (if any)")- except Exception: # noqa: BLE001- logger.warning("[AgentServer] embed_config cold load skipped", exc_info=True)-if is_enterprise():try:from jiuwenswarm.agents.harness.common.memory.config import (diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex f0d4058340..8894b2df76 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -1671,58 +1671,31 @@ async def _build_postgresql_async_engine():return Nonetry:from sqlalchemy import text- from sqlalchemy.ext.asyncio import create_async_engine+ from openjiuwen_runtime.foundation.db.postgresql_handler import PostgreSQLHandlerdb_port = os.getenv("GATEWAY_DB_PORT", "5432").strip()db_user = os.getenv("GATEWAY_DB_USER", "postgres").strip()db_password = os.getenv("GATEWAY_DB_PASSWORD", "").strip()db_name = os.getenv("GATEWAY_DB_NAME", "openjiuwen_gateway").strip()- _encoded_user = quote_plus(db_user)- _encoded_password = quote_plus(db_password)- server_url = (- f"postgresql+asyncpg://{_encoded_user}:{_encoded_password}"- f"@{db_host}:{db_port}/postgres"- )- temp_engine = create_async_engine(- server_url,- echo=False,- isolation_level="AUTOCOMMIT",- )-- async with temp_engine.connect() as conn:- result = await conn.execute(- text("SELECT 1 FROM pg_database WHERE datname = :name"),- {"name": db_name},- )- if result.scalar() is None:- quoted = db_name.replace('"', '""')- await conn.execute(text(f'CREATE DATABASE "{quoted}"'))- logger.info(- "[JiuWenSwarmDeepAdapter] PostgreSQL database created: %s",- db_name,- )- else:- logger.debug(- "[JiuWenSwarmDeepAdapter] PostgreSQL database already exists: %s",- db_name,- )- await temp_engine.dispose()-- db_url = (- f"postgresql+asyncpg://{_encoded_user}:{_encoded_password}"- f"@{db_host}:{db_port}/{db_name}"+ pg_schema = os.getenv("GATEWAY_PG_SCHEMA", "public").strip() or "public"+ handler = PostgreSQLHandler(+ host=db_host,+ port=int(db_port),+ database=db_name,+ schema=pg_schema,+ user=db_user,+ password=db_password,)- pool_kwargs = _gateway_db_pool_kwargs()- engine = create_async_engine(db_url, **pool_kwargs)+ # init_database 幂等:确保目标库与 schema 存在(schema 存在是 search_path 生效的前提)+ await handler.init_database()+ await handler.connect()+ engine = handler.get_engine()logger.info(- "[JiuWenSwarmDeepAdapter] checkpoint PostgreSQL engine created: %s:%s/%s "- "pool_size=%s max_overflow=%s pool_timeout=%s",+ "[JiuWenSwarmDeepAdapter] checkpoint PostgreSQL engine created: %s:%s/%s schema=%s",db_host,db_port,db_name,- pool_kwargs["pool_size"],- pool_kwargs["max_overflow"],- pool_kwargs["pool_timeout"],+ pg_schema,)# 确保 kv_store.value 列为 TEXT,避免 checkpoint 序列化数据被截断@@ -1806,14 +1779,15 @@ async def ensure_persistent_checkpointer() -> None:# 企业版:CHECKPOINT_DB_TYPE=mysql|postgresql 时改用对应库(复用 GATEWAY_DB_*)checkpoint_db_type = os.getenv("CHECKPOINT_DB_TYPE", "").strip().lower()if is_enterprise():- if checkpoint_db_type == "mysql":+ from openjiuwen_runtime.foundation.db.utils import is_mysql, is_postgresql+ if is_mysql(checkpoint_db_type):mysql_engine = await _build_mysql_async_engine()if mysql_engine is not None:conf["db_client"] = mysql_enginelogger.info("[JiuWenSwarmDeepAdapter] use mysql db_client for checkpointer")- elif checkpoint_db_type == "postgresql":+ elif is_postgresql(checkpoint_db_type):postgresql_engine = await _build_postgresql_async_engine()if postgresql_engine is not None:conf["db_client"] = postgresql_engine@@ -4709,14 +4683,16 @@ class JiuWenSwarmDeepAdapter:checkpoint_db_type = os.getenv("CHECKPOINT_DB_TYPE", "").strip().lower()if is_enterprise():- if checkpoint_db_type == "mysql":+ from openjiuwen_runtime.foundation.db.utils import is_mysql, is_postgresql++ if is_mysql(checkpoint_db_type):mysql_engine = await _build_mysql_async_engine()if mysql_engine is not None:conf["db_client"] = mysql_enginelogger.info("[JiuWenSwarmDeepAdapter] use mysql db_client for checkpointer")- elif checkpoint_db_type == "postgresql":+ elif is_postgresql(checkpoint_db_type):postgresql_engine = await _build_postgresql_async_engine()if postgresql_engine is not None:conf["db_client"] = postgresql_enginediff --git a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.pyindex afedd2f7f2..9b32ba69f3 100644--- a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py+++ b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py@@ -1,8 +1,5 @@-"""Gateway 本地库:企业配置读库(``GATEWAY_*``,不依赖 jiuwenclaw-ee)。--- 单机 / 未配远程库:aiosqlite 读本地文件(``resolve_gateway_db_path``)。-- 企业(``JIUWENSWARM_EDITION=enterprise``)且 ``GATEWAY_DB_HOST`` 有值:- 连 MySQL/PostgreSQL(与 Gateway 同一套 env),**禁止**再回退本地 sqlite。+"""AgentServer 企业配置读库:企业版专属+ 不支持sqlite,因为本地文件无法跨 pod(gateway跟agentserver) 共享。"""from __future__ import annotations@@ -11,96 +8,31 @@ import asyncioimport jsonimport osimport re-from pathlib import Path+from datetime import datetime, timezonefrom typing import Any-from urllib.parse import quote_plus--import aiosqlite-from jiuwenswarm.common.utils import get_user_workspace_dir, logger+from jiuwenswarm.common.utils import loggerfrom jiuwenswarm.gateway.config.enterprise.instance_scope import (apply_instance_scope as _apply_instance_scope,instance_scoped_store_names,list_records_requires_bound_instance,resolve_gateway_instance_id,)+from jiuwenswarm.gateway.config.enterprise.tables import init_all_tables++from openjiuwen_runtime.foundation.db.utils import is_mysql, is_postgresql+from openjiuwen_runtime.foundation.db.mysql_handler import MySQLHandler+from openjiuwen_runtime.foundation.db.postgresql_handler import PostgreSQLHandler+from .schemas import SLOT_ENTITY_TABLE, TemplateRefSlot-_DB_PATH: str | None = None_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")-# 与 catalog + cron_job 对齐;供测试与文档引用INSTANCE_SCOPED_TABLES = instance_scoped_store_names()-_remote_engine: Any | None = None-_remote_engine_key: str | None = None-_remote_engine_lock = asyncio.Lock()---def resolve_gateway_db_path() -> str | None:- """解析 Gateway SQLite 路径;未配置或不存在时返回 None。"""- global _DB_PATH- if _DB_PATH is not None:- return _DB_PATH-- explicit = (- os.getenv("GATEWAY_SQLITE_PATH", "").strip()- or os.getenv("JIUWENSWARM_GATEWAY_DB_PATH", "").strip()- or os.getenv("JIUWENCLAW_GATEWAY_DB_PATH", "").strip()- or os.getenv("MANAGER_WS_CLIENT_SQLITE_PATH", "").strip()- )- if explicit:- path = Path(explicit).expanduser()- if not path.is_absolute():- data_dir = (- os.getenv("JIUWENSWARM_DATA_DIR", "").strip()- or os.getenv("JIUWENCLAW_DATA_DIR", "").strip()- )- path = (Path(data_dir) / path) if data_dir else path- path = path.resolve()- if path.is_file():- _DB_PATH = str(path)- return _DB_PATH- logger.warning("[enterprise_config] GATEWAY_SQLITE_PATH not found: %s", path)- return None-- data_dir = (- os.getenv("JIUWENSWARM_DATA_DIR", "").strip()- or os.getenv("JIUWENCLAW_DATA_DIR", "").strip()- )- if data_dir:- root = Path(data_dir).expanduser().resolve()- for candidate in (- root / "gateway.db",- root / "agent_client.db",- root / "gateway" / "agent_client.db",- ):- if candidate.is_file():- _DB_PATH = str(candidate)- return _DB_PATH-- try:- from jiuwenswarm.common.config import get_config-- sqlite_path = (- (get_config().get("extensions") or {})- .get("agent_client_rest", {})- .get("database", {})- .get("sqlite_path")- )- if isinstance(sqlite_path, str) and sqlite_path.strip():- configured = Path(sqlite_path.strip()).expanduser()- if configured.is_file():- _DB_PATH = str(configured.resolve())- return _DB_PATH- except Exception as exc:- logger.debug("[enterprise_config] read sqlite_path from config failed: %s", exc)-- fallback = get_user_workspace_dir() / "gateway" / "agent_client.db"- if fallback.is_file():- _DB_PATH = str(fallback.resolve())- return _DB_PATH- return None+_remote_handler: Any | None = None+_remote_handler_key: str | None = None+_remote_handler_lock = asyncio.Lock()def resolve_jiuwenclaw_id() -> str | None:@@ -117,18 +49,6 @@ def apply_instance_scope(table: str, filters: dict[str, Any]) -> dict[str, Any]:)-def use_remote_gateway_db() -> bool:- """企业远程库:``is_enterprise()`` 且 ``GATEWAY_DB_HOST`` 非空。-- 单机版(``JIUWENSWARM_EDITION`` 非 enterprise)仍走本地 sqlite,行为不变。- """- from jiuwenswarm.common.local_env_config import is_enterprise-- if not is_enterprise():- return False- return bool(os.getenv("GATEWAY_DB_HOST", "").strip())--def _parse_json_string(value: str) -> Any:text = value.strip()if not text or text[0] not in "{[":@@ -140,11 +60,15 @@ def _parse_json_string(value: str) -> Any:def _row_to_dict(row: Any) -> dict[str, Any]:- """将 DB 行转为 dict;兼容 ``dict`` / aiosqlite.Row / SQLAlchemy Row。"""+ """将 DB 行转为 dict;兼容 ``dict`` / SQLAlchemy Row / ORM 实例。"""if isinstance(row, dict):items = dict(row)- else:+ elif hasattr(row, "keys") and callable(getattr(row, "keys")) and not hasattr(row, "__table__"):+ # SQLAlchemy Row(ORM 实例有 __table__,走 vars 分支)items = {k: row[k] for k in row.keys()}+ else:+ # ORM 实例:取 __dict__,剔除 SQLAlchemy 内部 _sa_ 字段+ items = {k: v for k, v in vars(row).items() if not k.startswith("_sa_")}out: dict[str, Any] = {}for key, value in items.items():if isinstance(value, str):@@ -153,182 +77,81 @@ def _row_to_dict(row: Any) -> dict[str, Any]:out[key] = valuereturn out+async def _dispose_remote_handler_unlocked() -> None:+ """释放进程内缓存的远程 handler(调用方须已持有 ``_remote_handler_lock``)。"""+ global _remote_handler, _remote_handler_key-def _sort_by_order(rows: list[dict[str, Any]], order_by: str) -> list[dict[str, Any]]:- text = order_by.strip()- if not text:- return rows-- parts = text.split(None, 1)- field = parts[0].strip()- reverse = False- if len(parts) > 1:- reverse = parts[1].strip().upper() == "DESC"- elif field.startswith("-"):- reverse = True- field = field[1:].strip()- if not field:- return rows-- def _key(row: dict[str, Any]) -> Any:- value = row.get(field)- if value is None:- return 0- try:- return int(value)- except (TypeError, ValueError):- return value-- return sorted(rows, key=_key, reverse=reverse)---def _gateway_db_pool_kwargs() -> dict[str, Any]:- def _int_env(*names: str, default: int) -> int:- for name in names:- raw = os.getenv(name, "").strip()- if not raw:- continue- try:- return int(raw)- except ValueError:- continue- return default-- return {- "pool_size": _int_env("GATEWAY_DB_POOL_SIZE", "RUNTIME_DB_POOL_SIZE", default=2),- "max_overflow": _int_env(- "GATEWAY_DB_MAX_OVERFLOW", "RUNTIME_DB_MAX_OVERFLOW", default=20- ),- "pool_timeout": _int_env(- "GATEWAY_DB_POOL_TIMEOUT", "RUNTIME_DB_POOL_TIMEOUT", default=30- ),- "pool_recycle": 3600,- "pool_pre_ping": True,- }---def _remote_db_type() -> str:- raw = (- os.getenv("GATEWAY_DB_TYPE", "").strip()- or os.getenv("DB_TYPE", "").strip()- or "mysql"- )- return raw.lower()---async def _dispose_remote_engine_unlocked() -> None:- """释放进程内缓存的远程 engine(调用方须已持有 ``_remote_engine_lock``)。"""- global _remote_engine, _remote_engine_key-- engine = _remote_engine- _remote_engine = None- _remote_engine_key = None- if engine is None:+ handler = _remote_handler+ _remote_handler = None+ _remote_handler_key = None+ if handler is None:returntry:- await engine.dispose()+ await handler.disconnect()except Exception as exc: # noqa: BLE001logger.warning(- "[enterprise_config] dispose remote gateway db engine failed: %s",+ "[enterprise_config] dispose remote gateway db handler failed: %s",exc,)-async def _dispose_remote_engine() -> None:- """释放进程内缓存的远程 engine 连接池。"""- async with _remote_engine_lock:- await _dispose_remote_engine_unlocked()---async def _get_remote_engine() -> Any:- """进程内复用远程读库 engine;连接失败抛错,不回退 sqlite。-- 配置(host/type/port/user/name)变化时先 ``dispose`` 旧 engine,避免连接池泄漏。- 检查 / dispose / 创建 / 赋值 由 ``_remote_engine_lock`` 串行化,避免并发覆盖泄漏。+async def _get_remote_handler() -> Any:+ """agentserver 读取共享的 gateway 配置库(远程 MySQL/PostgreSQL)。+ handler 在 agentserver 进程内缓存复用,避免每次查询重建连接池。+ pg 带 ``schema`` → search_path 自动隔离。配置变化时先 dispose 旧 handler。"""- global _remote_engine, _remote_engine_key+ global _remote_handler, _remote_handler_key- db_type = _remote_db_type()+ db_type = os.getenv("GATEWAY_DB_TYPE", "").strip()db_host = os.getenv("GATEWAY_DB_HOST", "").strip()db_port = os.getenv("GATEWAY_DB_PORT", "").strip()db_user = os.getenv("GATEWAY_DB_USER", "root").strip()db_password = os.getenv("GATEWAY_DB_PASSWORD", "").strip()db_name = os.getenv("GATEWAY_DB_NAME", "gateway").strip()- if not db_port:- db_port = "5432" if db_type in {"postgresql", "postgres", "pg"} else "3306"-- key = f"{db_type}|{db_host}|{db_port}|{db_user}|{db_name}"+ pg_schema = os.getenv("GATEWAY_PG_SCHEMA", "public").strip() or "public"+ key = f"{db_type}|{db_host}|{db_port}|{db_user}|{db_name}|{pg_schema}"- async with _remote_engine_lock:- if _remote_engine is not None and _remote_engine_key == key:- return _remote_engine+ async with _remote_handler_lock:+ if _remote_handler is not None and _remote_handler_key == key:+ return _remote_handler- if _remote_engine is not None:+ if _remote_handler is not None:logger.info(- "[enterprise_config] remote gateway db config changed (%s -> %s), disposing old engine",- _remote_engine_key,+ "[enterprise_config] gateway db config changed (%s -> %s), disposing old handler",+ _remote_handler_key,key,)- await _dispose_remote_engine_unlocked()-- from sqlalchemy.ext.asyncio import create_async_engine-- user = quote_plus(db_user)- password = quote_plus(db_password)- if db_type in {"postgresql", "postgres", "pg"}:- url = (- f"postgresql+asyncpg://{user}:{password}"- f"@{db_host}:{db_port}/{db_name}"+ await _dispose_remote_handler_unlocked()++ if is_postgresql(db_type):+ handler = PostgreSQLHandler(+ host=db_host,+ port=int(db_port),+ database=db_name,+ schema=pg_schema,+ user=db_user,+ password=db_password,)- elif db_type in {"mysql", "mariadb"}:- url = (- f"mysql+aiomysql://{user}:{password}"- f"@{db_host}:{db_port}/{db_name}?charset=utf8mb4"+ elif is_mysql(db_type):+ handler = MySQLHandler(+ host=db_host,+ port=int(db_port),+ database=db_name,+ user=db_user,+ password=db_password,)else:raise RuntimeError(- f"unsupported GATEWAY_DB_TYPE={db_type!r} for remote enterprise_config read; "- "use mysql or postgresql, or unset GATEWAY_DB_HOST for sqlite"+ f"unsupported GATEWAY_DB_TYPE={db_type!r}; use mysql or postgresql")- engine = create_async_engine(url, **_gateway_db_pool_kwargs())- _remote_engine = engine- _remote_engine_key = key- logger.info(- "[enterprise_config] remote gateway db reader ready: type=%s %s:%s/%s",- db_type,- db_host,- db_port,- db_name,- )- return engine---def _build_filter_clause(- query: dict[str, Any],- *,- named: bool,-) -> tuple[str, list[Any] | dict[str, Any]]:- where_parts: list[str] = []- if named:- params: dict[str, Any] = {}- for idx, (key, value) in enumerate(query.items()):- if not _SAFE_IDENT.fullmatch(str(key)):- continue- pname = f"p{idx}"- where_parts.append(f"{key} = :{pname}")- params[pname] = (1 if value else 0) if isinstance(value, bool) else value- clause = f" WHERE {' AND '.join(where_parts)}" if where_parts else ""- return clause, params-- params_list: list[Any] = []- for key, value in query.items():- if not _SAFE_IDENT.fullmatch(str(key)):- continue- where_parts.append(f"{key} = ?")- params_list.append((1 if value else 0) if isinstance(value, bool) else value)- clause = f" WHERE {' AND '.join(where_parts)}" if where_parts else ""- return clause, params_list+ await handler.init_database()+ await handler.connect()+ await init_all_tables(handler)+ _remote_handler = handler+ _remote_handler_key = key+ logger.info("[enterprise_config] gateway db reader ready: key=%s", key)+ return handlerasync def _list_records_remote(@@ -336,78 +159,38 @@ async def _list_records_remote(query: dict[str, Any],order_by: str,) -> list[dict[str, Any]]:- from sqlalchemy import text-- clause, params = _build_filter_clause(query, named=True)- sql = f"SELECT * FROM {table}{clause}"try:- engine = await _get_remote_engine()- async with engine.connect() as conn:- result = await conn.execute(text(sql), params)- rows = result.fetchall()- mapped = [_row_to_dict(r) for r in rows]- return _sort_by_order(mapped, order_by) if order_by else mapped+ handler = await _get_remote_handler()+ rows = await handler.list_records(+ table, query, limit=10_000, offset=0, order_by=order_by or None+ )+ return [_row_to_dict(r) for r in rows]except Exception as exc:logger.error(- "[enterprise_config] remote query %s failed (no sqlite fallback): %s",+ "[enterprise_config] query %s failed: %s",table,exc,)raise-async def _list_records_sqlite(- table: str,- query: dict[str, Any],- order_by: str,-) -> list[dict[str, Any]]:- db_path = resolve_gateway_db_path()- if not db_path:- return []-- clause, params = _build_filter_clause(query, named=False)- sql = f"SELECT * FROM {table}{clause}"- try:- async with aiosqlite.connect(db_path) as conn:- conn.row_factory = aiosqlite.Row- async with conn.execute(sql, params) as cursor:- rows = await cursor.fetchall()- result = [_row_to_dict(r) for r in rows]- return _sort_by_order(result, order_by) if order_by else result- except Exception as exc:- logger.warning("[enterprise_config] query %s failed: %s", table, exc)- return []--PERMISSIONS_CONFIG_TABLE = "permissions_config"-def is_gateway_db_available() -> bool:- """企业配置库是否可用:远程(有 HOST)或本地 sqlite 文件存在。"""- if use_remote_gateway_db():- return True- return bool(resolve_gateway_db_path())--async def upsert_permissions_config(body: dict[str, Any],*,source: str = "runtime_persist",) -> None:- """按 ``jiuwenclaw_id`` upsert ``permissions_config``(远程或本地 sqlite)。"""+ """按 ``jiuwenclaw_id`` upsert ``permissions_config``。"""jid = resolve_jiuwenclaw_id()if not jid:raise ValueError("JIUWENCLAW_ID is required for enterprise permissions persist")- from datetime import datetime, timezone-now = datetime.now(timezone.utc).isoformat()body_json = json.dumps(body, ensure_ascii=False)- if use_remote_gateway_db():- await _upsert_permissions_remote(jid, body_json, source=source, now=now)- return- await _upsert_permissions_sqlite(jid, body_json, source=source, now=now)+ await _upsert_permissions_remote(jid, body_json, source=source, now=now)async def _upsert_permissions_remote(@@ -417,97 +200,33 @@ async def _upsert_permissions_remote(source: str,now: str,) -> None:- from sqlalchemy import text-table = PERMISSIONS_CONFIG_TABLE- if not _SAFE_IDENT.fullmatch(table):- raise RuntimeError(f"invalid table name: {table!r}")-- engine = await _get_remote_engine()- async with engine.begin() as conn:- result = await conn.execute(- text(- f"SELECT id, revision FROM {table} WHERE jiuwenclaw_id = :jid"- ),- {"jid": jid},+ handler = await _get_remote_handler()+ existing = await handler.get(table, {"jiuwenclaw_id": jid})+ if existing is not None:+ revision = int(_row_to_dict(existing).get("revision") or 1) + 1+ await handler.update(+ table,+ {"jiuwenclaw_id": jid},+ {+ "body": body_json,+ "source": source,+ "revision": revision,+ "updated_at": now,+ },+ )+ else:+ await handler.create(+ table,+ {+ "jiuwenclaw_id": jid,+ "body": body_json,+ "source": source,+ "revision": 1,+ "created_at": now,+ "updated_at": now,+ },)- existing = result.fetchone()- if existing is not None:- revision = int(existing[1] or 1) + 1- await conn.execute(- text(- f"""- UPDATE {table}- SET body = :body, source = :source, revision = :revision,- updated_at = :updated_at- WHERE jiuwenclaw_id = :jid- """- ),- {- "body": body_json,- "source": source,- "revision": revision,- "updated_at": now,- "jid": jid,- },- )- else:- await conn.execute(- text(- f"""- INSERT INTO {table}- (jiuwenclaw_id, body, source, revision, created_at, updated_at)- VALUES (:jid, :body, :source, 1, :created_at, :updated_at)- """- ),- {- "jid": jid,- "body": body_json,- "source": source,- "created_at": now,- "updated_at": now,- },- )---async def _upsert_permissions_sqlite(- jid: str,- body_json: str,- *,- source: str,- now: str,-) -> None:- db_path = resolve_gateway_db_path()- if not db_path:- raise RuntimeError("gateway db not available")-- table = PERMISSIONS_CONFIG_TABLE- async with aiosqlite.connect(db_path) as conn:- async with conn.execute(- f"SELECT id, revision FROM {table} WHERE jiuwenclaw_id = ?",- (jid,),- ) as cursor:- existing = await cursor.fetchone()- if existing is not None:- revision = int(existing[1] or 1) + 1- await conn.execute(- f"""- UPDATE {table}- SET body = ?, source = ?, revision = ?, updated_at = ?- WHERE jiuwenclaw_id = ?- """,- (body_json, source, revision, now, jid),- )- else:- await conn.execute(- f"""- INSERT INTO {table}- (jiuwenclaw_id, body, source, revision, created_at, updated_at)- VALUES (?, ?, ?, 1, ?, ?)- """,- (jid, body_json, source, now, now),- )- await conn.commit()__all__ = (@@ -515,12 +234,9 @@ __all__ = ("PERMISSIONS_CONFIG_TABLE","apply_instance_scope","fetch_template_by_slot",- "is_gateway_db_available","list_records",- "resolve_gateway_db_path","resolve_jiuwenclaw_id","upsert_permissions_config",- "use_remote_gateway_db",)@@ -552,8 +268,6 @@ async def list_records(order_by: str = "",) -> list[dict[str, Any]]:"""列表查询;scoped 表自动按 ``jiuwenclaw_id`` 隔离。-- ``is_enterprise()`` + ``GATEWAY_DB_HOST`` 时走远程 MySQL/PG;否则走本地 sqlite。"""if not _SAFE_IDENT.fullmatch(table or ""):logger.warning("[enterprise_config] invalid table name: %r", table)@@ -568,6 +282,4 @@ async def list_records(return []query = apply_instance_scope(table, dict(filters or {}))- if use_remote_gateway_db():- return await _list_records_remote(table, query, order_by)- return await _list_records_sqlite(table, query, order_by)+ return await _list_records_remote(table, query, order_by)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.pyindex 4d6d3d467e..5eb5d5ff4c 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py@@ -14,7 +14,7 @@ from jiuwenswarm.infrastructure.log_masking.engine import LogMaskingEnginefrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import assert_jiuwenclaw_id_matches, format_ts, utc_now-from ...models.application_config_models import LOG_MASKING_RULE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.application_config_models import LOG_MASKING_RULE_TABLE_DEFfrom ...schemas.application_config_schemas import (LogMaskingRuleCreateRequest,LogMaskingRuleUpdateRequest,diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.pyindex 147429fb36..ee092d9b8d 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py@@ -11,7 +11,7 @@ from openjiuwen_runtime.foundation.db.handler import DBHandlerfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import format_ts, utc_now-from ...models.application_config_models import TASK_MEMORY_CONFIG_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.application_config_models import TASK_MEMORY_CONFIG_TABLE_DEF_TABLE = TASK_MEMORY_CONFIG_TABLE_DEF.table_namelogger = logging.getLogger(__name__)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.pyindex b4cc86f87e..7a94d00b25 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.config_effective_policy_models import (+from jiuwenswarm.gateway.config.enterprise.tables.config_effective_policy_models import (CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF,)from ...schemas.config_effective_policy_schemas import (diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.pyindex 6674e5e4d7..2bdd17a231 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.py@@ -18,7 +18,7 @@ from ...infrastructure.utils import (parse_iso_datetime,utc_now,)-from ...models.config_effective_policy_models import (+from jiuwenswarm.gateway.config.enterprise.tables.config_effective_policy_models import (CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF,CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.pyindex af804af2a3..4f29b19d73 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.py@@ -18,7 +18,7 @@ from ...infrastructure.utils import (parse_iso_datetime,utc_now,)-from ...models.config_effective_policy_models import (+from jiuwenswarm.gateway.config.enterprise.tables.config_effective_policy_models import (CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF,)from ...schemas.config_effective_policy_schemas import (diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.pyindex a164fd0930..3331e3b58f 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.py@@ -18,7 +18,7 @@ from ...infrastructure.utils import (parse_iso_datetime,utc_now,)-from ...models.config_effective_policy_models import (+from jiuwenswarm.gateway.config.enterprise.tables.config_effective_policy_models import (CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,)from ...schemas.config_effective_policy_schemas import (diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.pyindex 1532002e71..0765cb8709 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.instance_resource_models import INSTANCE_AGENT_RESOURCE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.instance_resource_models import INSTANCE_AGENT_RESOURCE_TABLE_DEFfrom ...schemas.instance_resource_schemas import InstanceAgentResourceUpsertRequest_TABLE = INSTANCE_AGENT_RESOURCE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.pyindex 87462e9090..ad0e7c9ac0 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py@@ -17,7 +17,7 @@ from ...infrastructure.utils import (parse_iso_datetime,utc_now,)-from ...models.template_models import AGENT_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import AGENT_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import AgentTemplateUpdateRequest_TABLE = AGENT_TEMPLATE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.pyindex 8e9fcfbb21..f3746148b1 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.template_models import EMBEDDING_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import EMBEDDING_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import EmbeddingTemplateUpdateRequest_TABLE = EMBEDDING_TEMPLATE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.pyindex 0071e6e144..f8cfe1eda2 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.template_models import EXTENSION_CONFIG_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import EXTENSION_CONFIG_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import (ExtensionConfigTemplateUpdateRequest,HookConfig,diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.pyindex ace1453b62..99b6d04aca 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.template_models import MODEL_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import MODEL_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import ModelTemplateUpdateRequest_TABLE = MODEL_TEMPLATE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.pyindex 25b95285ed..4924b56ef5 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py@@ -14,7 +14,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.template_models import SERVICE_CONFIG_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import SERVICE_CONFIG_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import ServiceConfigTemplateUpdateRequest_TABLE = SERVICE_CONFIG_TEMPLATE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.pyindex 4847bf7a33..9f3c703172 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py@@ -13,7 +13,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepfrom ...infrastructure.repository_access import require_enterprise_repositoryfrom ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.template_models import SKILL_WHITELIST_TEMPLATE_TABLE_DEF+from jiuwenswarm.gateway.config.enterprise.tables.template_models import SKILL_WHITELIST_TEMPLATE_TABLE_DEFfrom ...schemas.template_schemas import SkillWhitelistTemplateUpdateRequest, _validate_http_url_TABLE = SKILL_WHITELIST_TEMPLATE_TABLE_DEF.table_namediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.pyindex 140b681011..9aa8cd51f7 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py@@ -9,6 +9,8 @@ from typing import Optionalfrom pydantic import Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict+from openjiuwen_runtime.foundation.db.utils import is_sqlite+def _resolve_env_files() -> tuple[str | Path, ...]:"""解析可用的 .env 路径(优先 cwd,兼容 venv 安装布局)。"""@@ -138,7 +140,7 @@ class Settings(BaseSettings):@model_validator(mode="after")def validate_db_fields(self) -> "Settings":# 如果是 SQLite,不需要校验连接参数- if self.gateway_db_type == "sqlite":+ if is_sqlite(self.gateway_db_type):# 如果没传路径,自动设置默认值if self.gateway_sqlite_path is None or self.gateway_sqlite_path.strip() == "":self.gateway_sqlite_path = "gateway.db"diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/db.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/db.pyindex 57035ee6c8..c405163dc2 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/db.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/db.py@@ -14,9 +14,10 @@ from openjiuwen_runtime.foundation.db.mysql_handler import MySQLHandlerfrom openjiuwen_runtime.foundation.db import postgresql_handlerfrom openjiuwen_runtime.foundation.db.postgresql_handler import PostgreSQLHandlerfrom openjiuwen_runtime.foundation.db.sqlite_handler import SQLiteHandler+from openjiuwen_runtime.foundation.db.utils import is_mysql, is_postgresql, is_sqlitefrom openjiuwen_runtime.foundation.log import get_logger-from ..models.table_init import init_all_tables+from jiuwenswarm.gateway.config.enterprise.tables.table_init import init_all_tablesfrom .config import Settings, get_settingslogger = get_logger(__name__)@@ -67,7 +68,7 @@ class Database:def config_summary(self) -> dict[str, Any]:cfg = self.settingsdb_type = str(cfg.gateway_db_type or "").strip().lower() or "sqlite"- if db_type == "sqlite":+ if is_sqlite(db_type):result = {"db_type": db_type,"sqlite_path": str(self.resolve_sqlite_path()),@@ -79,7 +80,7 @@ class Database:"port": cfg.gateway_db_port,"database": cfg.gateway_db_name,}- if db_type == "postgresql":+ if is_postgresql(db_type):result["schema"] = cfg.gateway_pg_schemareturn result@@ -126,11 +127,11 @@ class Database:db_type = str(cfg.gateway_db_type or "").strip().lower() or "sqlite"logger.info("Using database: %s", db_type)- if db_type == "sqlite":+ if is_sqlite(db_type):self._handler = self._create_sqlite_handler()- elif db_type == "mysql":+ elif is_mysql(db_type):self._handler = self._create_mysql_handler()- elif db_type in ("postgresql", "postgres", "pg"):+ elif is_postgresql(db_type):self._handler = self._create_pg_handler()else:raise ValueError(diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.pyindex bde5d4f539..1dc9855f89 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py@@ -18,7 +18,7 @@ from openjiuwen_runtime.foundation.security import link_authfrom ..infrastructure.repository_access import require_enterprise_repositoryfrom ..infrastructure.utils import utc_now-from ..models.key_models import (+from jiuwenswarm.gateway.config.enterprise.tables.key_models import (GATEWAY_ENC_KEYPAIR_TABLE_DEF,GATEWAY_SIGN_KEYPAIR_TABLE_DEF,MANAGER_SIGN_PUBKEY_TABLE_DEF,diff --git a/tests/unit_tests/gateway/test_app_gateway_external_config.py b/tests/unit_tests/gateway/test_app_gateway_external_config.pyindex f71500ec80..68ad75bfba 100644--- a/tests/unit_tests/gateway/test_app_gateway_external_config.py+++ b/tests/unit_tests/gateway/test_app_gateway_external_config.py@@ -1,49 +1,35 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved"""app_gateway 企业版/外置 Runtime 配置下发跳过逻辑。"""from __future__ import annotations-from unittest.mock import patch-from jiuwenswarm.gateway.app_gateway import _uses_external_agent_configdef test_uses_external_agent_config_false_for_personal(monkeypatch) -> None:+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)monkeypatch.delenv("GATEWAY_RUNTIME_MANAGER_URL", raising=False)- with patch(- "jiuwenswarm.gateway.edition.is_gateway_enterprise",- return_value=False,- ):- assert _uses_external_agent_config() is False+ assert _uses_external_agent_config() is Falsedef test_uses_external_agent_config_true_for_enterprise(monkeypatch) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")monkeypatch.delenv("GATEWAY_RUNTIME_MANAGER_URL", raising=False)- with patch(- "jiuwenswarm.gateway.edition.is_gateway_enterprise",- return_value=True,- ):- assert _uses_external_agent_config() is True+ assert _uses_external_agent_config() is Truedef test_uses_external_agent_config_true_when_runtime_manager_url_set(monkeypatch,) -> None:+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", "http://runtime-manager:8091")- with patch(- "jiuwenswarm.gateway.edition.is_gateway_enterprise",- return_value=False,- ):- assert _uses_external_agent_config() is True+ assert _uses_external_agent_config() is Truedef test_uses_external_agent_config_ignores_blank_runtime_manager_url(monkeypatch,) -> None:+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", " ")- with patch(- "jiuwenswarm.gateway.edition.is_gateway_enterprise",- return_value=False,- ):- assert _uses_external_agent_config() is False+ assert _uses_external_agent_config() is Falsediff --git a/tests/unit_tests/gateway/test_channel_config_repository.py b/tests/unit_tests/gateway/test_channel_config_repository.pyindex e7a34c43f9..0a6197fe45 100644--- a/tests/unit_tests/gateway/test_channel_config_repository.py+++ b/tests/unit_tests/gateway/test_channel_config_repository.py@@ -296,11 +296,12 @@ async def test_file_backend_replace_subsection_writes_yaml(tmp_path: Path) -> No@pytest.mark.asyncio-async def test_create_channel_config_repository_selects_codec() -> None:+async def test_create_channel_config_repository_selects_codec(monkeypatch) -> None:from jiuwenswarm.gateway.storage_assembly import create_channel_config_repositorystore = InMemoryPersistentBackend()- personal = create_channel_config_repository(store, "personal")+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)+ personal = create_channel_config_repository(store)await personal.upsert(ChannelConfig(channel_id="web", body={"enabled": True}))yaml_row = await store.get("channel_config", {"id": "web"})assert yaml_row is not None@@ -308,8 +309,9 @@ async def test_create_channel_config_repository_selects_codec() -> None:assert yaml_row["enabled"] is Truedb_store = InMemoryPersistentBackend()+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")enterprise = create_channel_config_repository(- db_store, "enterprise", instance_id="inst-1"+ db_store, instance_id="inst-1")await enterprise.upsert(ChannelConfig(channel_id="web", body={"enabled": True}))db_row = await db_store.get(diff --git a/tests/unit_tests/gateway/test_section_config_repositories.py b/tests/unit_tests/gateway/test_section_config_repositories.pyindex 9c6dfddeb7..3147bb21a6 100644--- a/tests/unit_tests/gateway/test_section_config_repositories.py+++ b/tests/unit_tests/gateway/test_section_config_repositories.py@@ -17,7 +17,6 @@ from jiuwenswarm.gateway.config.section import (DbFlatSectionCodec,YamlSectionCodec,)-from jiuwenswarm.gateway.edition import EDITION_ENTERPRISE, EDITION_PERSONALfrom jiuwenswarm.gateway.storage.backends.file_persistent import FilePersistentBackendfrom jiuwenswarm.gateway.storage.backends.memory_persistent import InMemoryPersistentBackendfrom jiuwenswarm.gateway.storage_assembly.layouts import build_gateway_store_registry@@ -168,27 +167,27 @@ async def test_section_yaml_file_overlay(tmp_path) -> None:assert "bar: 2" in text-def test_factory_codec_selection() -> None:+def test_factory_codec_selection(monkeypatch) -> None:store = InMemoryPersistentBackend()- personal = create_permissions_config_repository(store, EDITION_PERSONAL)- enterprise = create_permissions_config_repository(- store, EDITION_ENTERPRISE, instance_id="x"- )+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)+ personal = create_permissions_config_repository(store)assert isinstance(personal._inner._codec, YamlSectionCodec)+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ enterprise = create_permissions_config_repository(store, instance_id="x")assert isinstance(enterprise._inner._codec, DbBodySectionCodec)- log_personal = create_logging_config_repository(store, EDITION_PERSONAL)- log_enterprise = create_logging_config_repository(- store, EDITION_ENTERPRISE, instance_id="x"- )+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)+ log_personal = create_logging_config_repository(store)assert isinstance(log_personal._inner._codec, YamlSectionCodec)+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ log_enterprise = create_logging_config_repository(store, instance_id="x")assert isinstance(log_enterprise._inner._codec, DbFlatSectionCodec)- mem_personal = create_memory_config_repository(store, EDITION_PERSONAL)- mem_enterprise = create_memory_config_repository(- store, EDITION_ENTERPRISE, instance_id="x"- )+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)+ mem_personal = create_memory_config_repository(store)assert isinstance(mem_personal._inner._codec, YamlSectionCodec)+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ mem_enterprise = create_memory_config_repository(store, instance_id="x")assert isinstance(mem_enterprise._inner._codec, DbBodySectionCodec)@pytest.mark.asyncio@@ -242,7 +241,7 @@ async def test_preferred_language_scalar_overlay(tmp_path) -> None:assert "preferred_language:\n preferred_language:" not in text-def test_new_section_factory_codec_selection() -> None:+def test_new_section_factory_codec_selection(monkeypatch) -> None:store = InMemoryPersistentBackend()for factory in (create_heartbeat_config_repository,@@ -250,10 +249,12 @@ def test_new_section_factory_codec_selection() -> None:create_preferred_language_config_repository,create_a2ui_config_repository,):- personal = factory(store, EDITION_PERSONAL)+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)+ personal = factory(store)assert isinstance(personal._inner._codec, YamlSectionCodec)+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")try:- factory(store, EDITION_ENTERPRISE, instance_id="x")+ factory(store, instance_id="x")raise AssertionError("expected personal-only ValueError")except ValueError as exc:assert "personal-only" in str(exc)diff --git a/tests/unit_tests/test_history.py b/tests/unit_tests/test_history.pyindex 54fe28ace5..d803b5f373 100644--- a/tests/unit_tests/test_history.py+++ b/tests/unit_tests/test_history.py@@ -6,7 +6,6 @@ import pytestfrom jiuwenswarm.channels.web.history_store import (ChatHistoryStore,- default_enterprise_history_db_path,get_session_detail_sync,list_sessions_sync,make_history_callback,@@ -303,10 +302,10 @@ def test_mysql_without_host_unavailable(monkeypatch: pytest.MonkeyPatch) -> Nonedef test_resolve_history_db_type_prefers_web_db_type(monkeypatch: pytest.MonkeyPatch,) -> None:- monkeypatch.setenv("WEB_DB_TYPE", "sqlite")+ monkeypatch.setenv("WEB_DB_TYPE", "postgresql")monkeypatch.setenv("DB_TYPE", "mysql")monkeypatch.delenv("WEB_DB_HOST", raising=False)- assert resolve_history_db_type() == "sqlite"+ assert resolve_history_db_type() == "postgresql"def test_resolve_history_db_type_host_implies_mysql(@@ -327,7 +326,7 @@ def test_resolve_history_db_type_follows_deployment_mode(monkeypatch.setenv("DEPLOYMENT_MODE", "distributed")assert resolve_history_db_type() == "mysql"monkeypatch.setenv("DEPLOYMENT_MODE", "standalone")- assert resolve_history_db_type() == "sqlite"+ assert resolve_history_db_type() == "memory"@pytest.mark.asyncioasync def test_callback_uplink_request_id_in_payload() -> None:@@ -363,13 +362,7 @@ async def test_callback_uplink_request_id_in_payload() -> None:await store.close()-def test_default_enterprise_history_db_path_is_web_history_db() -> None:- path = default_enterprise_history_db_path()- assert path.endswith("web_history.db")---async def test_sync_read_missing_sqlite_file(tmp_path) -> None:+def test_sync_read_missing_sqlite_file(tmp_path) -> None:missing = tmp_path / "missing.db"assert list_sessions_sync(missing) == []assert get_session_detail_sync(missing, "x") is None