Skip to content

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

给部署工具打个patch,绕过管理端,直接给gateway和agent-runtime下发配置

chen huie3932dd87c71
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.example
index eda06a3d65..9fd55b3ba0 100644
--- a/deploy/enterprise/.env.example
+++ b/deploy/enterprise/.env.example
@@ -208,7 +208,7 @@ RABBITMQ_MGR_NODE_PORT=
# ====================== Redis 服务配置 ======================
-# Redis 部署形态: standalone(单机/主从) | cluster(三主三从 Cluster)
+# Redis 部署形态: standalone(单机) | cluster(集群)
REDIS_MODE="standalone"
# 外部 Redis 服务连接地址:
@@ -304,9 +304,6 @@ GATEWAY_CLAW_WS_PING_TIMEOUT="20.0" # WebSocket 心跳无响应超时阈值
# per_chat_bot_user - 按用户维度隔离会话(每个用户独立会话)
GATEWAY_SESSION_MAP_SCOPE="per_chat_bot_user"
-# 实例标识,留空则Manager在注册时分配,若需复用已有或固定实例标识,请在.env.custom中配置
-JIUWENCLAW_ID=""
-
# Gateway 服务的容器最小保证 CPU:0.5核(500毫核),K8s 必须分配足够CPU才能调度启动
GATEWAY_CPU_REQUEST=500m
@@ -464,31 +461,11 @@ MANAGER_SERVER_MEMORY_LIMIT=1Gi
# Manager 前端模块容器镜像地址
MANAGER_WEB_IMAGE=""
-# 控制是否启动Manager 前端模块
-IS_UP_MANAGER_WEB=false
-
-# 产品形态:personal 或 enterprise。两种模式均通过 User Web NodePort 独立提供。
-# personal:跳过企业登录;enterprise:启用企业登录及用户/组织/组网/Agent 面板。
-JIUWENSWARM_EDITION=enterprise
-
-# 是否模拟企业登录认证。默认 true,使用内置调试身份和三元组,不访问客户身份服务。
-# false:正式身份认证模式,依赖客户侧 manager ID 认证服务。
-# personal 模式始终跳过企业登录,此参数仅在 enterprise 模式生效。
-LOGIN_AUTH_SIMULATE=true
-
-# 当前 User Web 制品是否包含可选的认证模拟插件。内部联调制品为 true;
-# 客户正式制品构建时设为 false,且必须同时设置 LOGIN_AUTH_SIMULATE=false。
-LOGIN_AUTH_SIMULATE_AVAILABLE=true
-
# 正式模式依赖的认证及 Manager 业务接口。留空时暂时使用部署工具现有的集群内
# jiuwenclaw-identity 和 jiuwenclaw-manager-server;客户接口就绪后改为客户地址。
USER_WEB_IDP_TARGET=""
USER_WEB_MANAGER_TARGET=""
-# 已废弃,仅兼容旧配置;新部署请使用 JIUWENSWARM_EDITION
-# USER_WEB_MODE=personal
-# ENABLE_USER_WEB_EMBEDDING=false
-
# Manager 前端模块对外暴露的主机端口
# 不设置就自动寻找空闲端口,如需要设置,请确保该端口的唯一性(范围: 30000-32767)
# IS_UP_MANAGER_WEB=false的时候,该参数失效
diff --git a/deploy/enterprise/README.md b/deploy/enterprise/README.md
index 8eb5949e1e..cd7857b77c 100644
--- a/deploy/enterprise/README.md
+++ b/deploy/enterprise/README.md
@@ -681,103 +681,6 @@ Web 为 JiuwenSwarm 企业版面向终端用户的对话可视化前端,用于
```
-#### 4.3.1 用户面入口模式
-
-用户面通过 `USER_WEB_MODE` 选择产品形态:
-
-```bash
-# personal:独立用户面,跳过企业登录
-# enterprise:独立用户面,启用企业登录和用户上下文面板
-USER_WEB_MODE=personal
-```
-
-登录认证模拟由独立参数控制:
-
-```bash
-# 默认 true:企业模式使用 debug-user/debug-group/debug-gateway/debug-agent,
-# 不请求 Identity/Manager 用户目录接口。
-LOGIN_AUTH_SIMULATE=true
-
-# 正式模式:调用客户侧 manager 提供的 ID 认证和用户目录接口。
-LOGIN_AUTH_SIMULATE=false
-
-# 暂未配置客户接口时可以留空,部署工具会回落到当前集群内 Identity/Manager。
-USER_WEB_IDP_TARGET=""
-USER_WEB_MANAGER_TARGET=""
-```
-
-`LOGIN_AUTH_SIMULATE` 仅接受 `true` 或 `false`。在 `personal` 模式下用户面始终跳过
-企业登录;若同时配置 `LOGIN_AUTH_SIMULATE=false`,部署和启动日志会提示该参数冲突且
-不会改变 personal 行为。正式模式启动时会分别检查 ID 认证服务和 Manager 业务接口的
-连通性并输出明确日志。
-
-认证模拟实现按插件装配。内部联调制品保持 `LOGIN_AUTH_SIMULATE_AVAILABLE=true`;
-客户正式制品使用前端 `npm run build:customer` 构建,并配置
-`LOGIN_AUTH_SIMULATE_AVAILABLE=false`、`LOGIN_AUTH_SIMULATE=false`。客户构建不会将
-`src/auth/simulate/` 内的默认用户和三元组实现打入静态产物,该目录也可从客户源码包
-直接剥离。若不含插件的制品误开模拟认证,部署检查和 User Web 启动均会明确拒绝启动。
-
-`personal` 和 `enterprise` 均通过 User Web NodePort 提供独立入口,不要求部署 Manager Web。
-`enterprise` 仅控制企业登录及用户、组织、组网、Agent 上下文面板。模拟模式完全不依赖
-Manager;正式模式保留对 Manager ID 认证及业务目录接口的调用。
-
-当前客户接口尚未提供时,目标地址留空会使用以下集群内默认值:
-
-```bash
-USER_WEB_IDP_TARGET=http://jiuwenclaw-identity:8770
-USER_WEB_MANAGER_TARGET=http://jiuwenclaw-manager-server:8765
-```
-
-这两个组件仅作为现阶段正式模式联调后端,可通过 `./deploy.sh up manager` 单独部署;
-无参数默认交付不再部署 Manager。客户接口就绪后,只需覆盖两个目标地址,不改变现有接口路径。
-
-旧配置 `ENABLE_USER_WEB_EMBEDDING` 仅作兼容输入:`true` 等价于
-`USER_WEB_MODE=enterprise`,`false` 等价于 `USER_WEB_MODE=personal`。新部署不应继续使用。
-
-User Web 使用以下同源代理路由访问认证、Manager 业务接口和 Gateway:
-
-| 路径 | 目标服务 | 用途 |
-|---|---|---|
-| `/idp/*` | Identity Center | 登录、刷新令牌和用户信息 |
-| `/api/*` | Manager Server | 管理面与用户目录接口 |
-| `/chat/*` | User Web HTTP | 用户面对话界面 |
-| `/ws*` | Gateway WebSocket | 用户面默认消息通道 |
-| `/gateway-api/*` | Gateway Web HTTP/SSE | 用户面 REST/SSE 通道,与 Manager `/api/v1` 隔离 |
-
-| `/file-api/*`、`/share-api/*` | Gateway Web HTTP | 文件与分享接口 |
-
-Manager Web 与 `/chat/` 使用同一浏览器源,登录状态由 Manager Web 统一管理。User Web
-只消费 Manager Web 注入的用户、组织、Bot 和组网上下文,不提供另一套登录入口。
-
-#### 4.3.2 升级已有 MySQL 数据库
-
-全新数据库会按当前表定义自动建表,不需要手工迁移。复用旧版 Manager MySQL
-数据库并升级到包含 Agent 工作区策略的版本时,先检查策略表是否已有
-`workspace_dir`:
-
-```sql
-SELECT COLUMN_NAME
-FROM information_schema.COLUMNS
-WHERE TABLE_SCHEMA = '<manager数据库名>'
- AND TABLE_NAME = 'config_effective_agent_policy'
- AND COLUMN_NAME = 'workspace_dir';
-```
-
-仅当表存在且查询结果为空时执行:
-
-```sql
-ALTER TABLE <manager数据库名>.config_effective_agent_policy
-ADD COLUMN workspace_dir VARCHAR(512) NULL;
-```
-
-`workspace_dir` 是 Agent 策略的数据目录逻辑键,可使用 `${user_id}`、
-`${group_id}`、`${bot_id}` 等模板变量。它不参与用户登录或 JWT 验签。
-
-Identity Center 使用全新 MySQL 数据库时不需要迁移。若复用曾运行旧版联合认证的
-数据库,应先确认 `federated_identity` 表已经包含 `identity_key`;该字段需要根据
-原三元组生成摘要并建立唯一索引,不能只增加一个空字段。存在旧联合身份数据时应先
-备份并使用对应 Runtime 版本的迁移流程,部署工具不会自动修改业务身份数据。
-
## 5 服务异常排查
系统服务运行异常时,可按以下步骤逐层定位故障根因:
diff --git a/deploy/enterprise/args_handler.sh b/deploy/enterprise/args_handler.sh
index 7112b0d74a..e11adf9997 100755
--- a/deploy/enterprise/args_handler.sh
+++ b/deploy/enterprise/args_handler.sh
@@ -51,12 +51,7 @@ parse_args() {
}
process_modules() {
- # personal 默认不带 Manager;enterprise 需要 Manager 作为统一入口
- if [[ "${DEPLOY_VARS["JIUWENSWARM_EDITION"]:-enterprise}" == "enterprise" ]]; then
- MODULES=("GATEWAY" "WEB" "MANAGER" "RUNTIME")
- else
- MODULES=("GATEWAY" "WEB" "RUNTIME")
- fi
+ MODULES=("GATEWAY" "WEB" "RUNTIME")
}
# Print help info and exit
diff --git a/deploy/enterprise/check_handler.sh b/deploy/enterprise/check_handler.sh
index 9da02dd66e..c4b736e546 100755
--- a/deploy/enterprise/check_handler.sh
+++ b/deploy/enterprise/check_handler.sh
@@ -9,53 +9,6 @@ check_cmd() {
fi
}
-check_boolean_value() {
- local name="$1"
- local value="${DEPLOY_VARS["${name}"]:-}"
- if [[ "${value}" != "true" && "${value}" != "false" ]]; then
- error "${name} must be true or false, current value: ${value}"
- fi
-}
-
-check_jiuwenswarm_edition_config() {
- local edition="${DEPLOY_VARS["JIUWENSWARM_EDITION"]:-enterprise}"
- if [[ "${edition}" != "personal" && "${edition}" != "enterprise" ]]; then
- error "JIUWENSWARM_EDITION must be personal or enterprise, current value: ${edition}"
- fi
- check_boolean_value "IS_UP_MANAGER_WEB"
- check_boolean_value "LOGIN_AUTH_SIMULATE"
- check_boolean_value "LOGIN_AUTH_SIMULATE_AVAILABLE"
- if [[ "${edition}" == "enterprise" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "true" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE_AVAILABLE"]}" == "false" ]]; then
- error "配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;请设置 LOGIN_AUTH_SIMULATE=false"
- fi
- if [[ "${edition}" == "personal" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
- warning "配置冲突:JIUWENSWARM_EDITION=personal 始终跳过企业登录;LOGIN_AUTH_SIMULATE=false 不会启用正式身份认证"
- fi
- if [[ "${edition}" == "enterprise" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
- if [[ -z "${DEPLOY_VARS["USER_WEB_IDP_TARGET"]:-}" ]]; then
- error "正式身份认证模式缺少 USER_WEB_IDP_TARGET"
- fi
- if [[ -z "${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]:-}" ]]; then
- error "正式身份认证模式缺少 USER_WEB_MANAGER_TARGET"
- fi
- fi
-}
-
-check_user_web_mode_config() {
- check_jiuwenswarm_edition_config
-}
-
-module_is_selected() {
- local expected="$1"
- local module=""
- for module in "${MODULES[@]}"; do
- if [ "${module}" == "${expected}" ]; then
- return 0
- fi
- done
- return 1
-}
-
check_yq() {
local YQ_VERSION=$(yq --version 2>&1)
@@ -509,12 +462,10 @@ check_gateway_up_dependency(){
check_if_db_up
check_if_jina_up
-
ensure_redis_up
}
check_web_up_dependency(){
- check_jiuwenswarm_edition_config
check_if_db_up
check_if_obs_up
@@ -524,7 +475,6 @@ check_web_up_dependency(){
}
check_manager_up_dependency(){
- check_jiuwenswarm_edition_config
#check_if_rabbitmq_up
check_if_db_up
}
diff --git a/deploy/enterprise/deploy.sh b/deploy/enterprise/deploy.sh
index 3a26f36d0e..751ae6df48 100755
--- a/deploy/enterprise/deploy.sh
+++ b/deploy/enterprise/deploy.sh
@@ -23,6 +23,7 @@ source "gateway_handler.sh"
source "manager_handler.sh"
source "web_handler.sh"
source "runtime_handler.sh"
+source "patch_handler.sh"
process_up() {
# MODULES是ALL_MODULES的子集,启动顺序正着来
@@ -92,52 +93,6 @@ process_restart() {
# ==================== Main function ====================
main() {
read_env_from_file "${CUSTOM_ENV_FILE}" "DEPLOY_VARS"
-
- # JIUWENSWARM_EDITION 是产品形态的唯一开关;USER_WEB_MODE / ENABLE_USER_WEB_EMBEDDING 仅作兼容输入。
- if [[ -z "${DEPLOY_VARS["JIUWENSWARM_EDITION"]:-}" ]]; then
- if [[ -n "${DEPLOY_VARS["USER_WEB_MODE"]:-}" ]]; then
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="${DEPLOY_VARS["USER_WEB_MODE"]}"
- warning "USER_WEB_MODE is deprecated; use JIUWENSWARM_EDITION=${DEPLOY_VARS["JIUWENSWARM_EDITION"]}"
- elif [[ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]:-false}" == "true" ]]; then
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="enterprise"
- warning "ENABLE_USER_WEB_EMBEDDING is deprecated; use JIUWENSWARM_EDITION=enterprise"
- else
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="enterprise"
- fi
- fi
- DEPLOY_VARS["USER_WEB_MODE"]="${DEPLOY_VARS["JIUWENSWARM_EDITION"]}"
- DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]=$(
- [[ "${DEPLOY_VARS["JIUWENSWARM_EDITION"]}" == "enterprise" ]] && printf true || printf false
- )
- if [[ -z "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]:-}" ]]; then
- DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="true"
- fi
- local user_web_idp_defaulted="false"
- local user_web_manager_defaulted="false"
- if [[ -z "${DEPLOY_VARS["USER_WEB_IDP_TARGET"]:-}" ]]; then
- DEPLOY_VARS["USER_WEB_IDP_TARGET"]="http://${DEPLOY_VARS["IDENTITY_NAME"]}:${DEPLOY_VARS["IDENTITY_REST_PORT"]}"
- user_web_idp_defaulted="true"
- fi
- if [[ -z "${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]:-}" ]]; then
- DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]="http://${DEPLOY_VARS["MANAGER_SERVER_NAME"]}:${DEPLOY_VARS["MANAGER_REST_PORT"]}"
- user_web_manager_defaulted="true"
- fi
- if [[ "${DEPLOY_VARS["JIUWENSWARM_EDITION"]}" == "enterprise" ]]; then
- if [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "true" ]]; then
- info "【登录认证模拟调试模式已开启】"
- elif [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
- info "【正式身份认证模式,依赖manager ID认证服务】"
- if [[ "${user_web_idp_defaulted}" == "true" ]]; then
- info "USER_WEB_IDP_TARGET 未配置,暂使用当前集群 Identity:${DEPLOY_VARS["USER_WEB_IDP_TARGET"]}"
- fi
- if [[ "${user_web_manager_defaulted}" == "true" ]]; then
- info "USER_WEB_MANAGER_TARGET 未配置,暂使用当前集群 Manager:${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]}"
- fi
- fi
- elif [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
- warning "配置冲突:personal 模式仍将跳过企业登录认证"
- fi
-
parse_args "$@"
detect_os
check_dependency
diff --git a/deploy/enterprise/gateway_handler.sh b/deploy/enterprise/gateway_handler.sh
index 1ea3d16146..45b4bd32b5 100755
--- a/deploy/enterprise/gateway_handler.sh
+++ b/deploy/enterprise/gateway_handler.sh
@@ -6,13 +6,14 @@ 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 yaml_file="${CONFIG["GATEWAY_ENV_YAML_FILE"]}"
render_config_template "${env_template_file}" "${env_file}" "DEPLOY_VARS"
echo "CLAW_MOUNT_TYPE=${DEPLOY_VARS["CLAW_MOUNT_TYPE"]}" >> "${env_file}"
if [ "${DEPLOY_VARS["CLAW_MOUNT_TYPE"]}" == "nfs" ]; then
echo "CLAW_NFS_SERVER=${DEPLOY_VARS["NFS_SERVER_ADDR"]}" >> "${env_file}"
- echo "CLAW_NFS_PATH=${DEPLOY_VARS["NFS_SHARE_PATH"]}/jiuwenclaw" >> "${env_file}"
+ echo "CLAW_NFS_PATH=${DEPLOY_VARS["NFS_SHARE_PATH"]}/jiuwenclaw" >> "${env_file}"
else
echo "CLAW_PVC=${DEPLOY_VARS["CLAW_PVC"]}" >> "${env_file}"
fi
@@ -25,19 +26,22 @@ gen_gateway_env_file() {
| awk -F'=' '$2 != ""' \
| sort > "${env_file}.tmp" && mv -f "${env_file}.tmp" "${env_file}"
- kubectl create configmap -n ${namespace} ${envfile_name} --from-file=.env=${env_file} --dry-run=client -o yaml | yq eval 'del(.metadata.creationTimestamp)' > ${CONFIG_DIR}/gateway-envfile.configmap.yaml
+ kubectl create configmap -n "${namespace}" "${envfile_name}" \
+ --from-file=.env="${env_file}" \
+ --dry-run=client -o yaml \
+ | yq eval 'del(.metadata.creationTimestamp)' > "${yaml_file}"
}
gen_gateway_config_file() {
local field_name="feishu"
- local template_file="${TEMPLATE_DIR}/gateway-config.template.yaml"
+ local template_file="${CONFIG["GATEWAY_CONFIG_TEMPLATE_FILE"]}"
local file="${CONFIG["GATEWAY_CONFIG_FILE"]}"
+ local yaml_file="${CONFIG["GATEWAY_CONFIG_YAML_FILE"]}"
local namespace="${DEPLOY_VARS["NAMESPACE"]}"
local conf_name="${DEPLOY_VARS["GATEWAY_CONFIG_MAP_NAME"]}"
- local conf_file="${CONFIG["GATEWAY_CONFIG_FILE"]}"
-
+
info "GATEWAY_CONFIG_TEMPLATE_FILE: ${template_file}"
- render_config_template ${template_file} ${file} "DEPLOY_VARS"
+ render_config_template "${template_file}" "${file}" "DEPLOY_VARS"
# Clear configuration
yq eval ".channels.${field_name} = {}" -i "${file}"
@@ -60,8 +64,11 @@ gen_gateway_config_file() {
yq eval ".channels.${field_name}.${bot_name}.enabled = true" -i "${file}"
done
- success "ConfigMap file generation completed: ${file}"
- kubectl create configmap -n ${namespace} ${conf_name} --from-file=config.yaml=${conf_file} --dry-run=client -o yaml | yq eval 'del(.metadata.creationTimestamp)' > ${CONFIG_DIR}/gateway-config.configmap.yaml
+ success "Gateway config rendered: ${file}; ConfigMap yaml: ${yaml_file}"
+ kubectl create configmap -n "${namespace}" "${conf_name}" \
+ --from-file=config.yaml="${file}" \
+ --dry-run=client -o yaml \
+ | yq eval 'del(.metadata.creationTimestamp)' > "${yaml_file}"
}
gen_gateway_file() {
@@ -71,37 +78,29 @@ gen_gateway_file() {
local enable_gw_lable="${DEPLOY_VARS["GATEWAY_SCHED_LABEL_ENABLED"]}"
render_config_template "${template_file}" "${file}" "DEPLOY_VARS"
- enable_dev_mode_if_needed ${file} gateway
+ enable_dev_mode_if_needed "${file}" gateway
# No need to install packages
if [[ "${mode}" == "dev" && -n "${DEPLOY_VARS["CLAW_CODE_PATH"]:-}" ]]; then
local claw_code="${DEPLOY_VARS["CLAW_CODE_PATH"]}"
- yq eval '.dependencies = {}' -i ${claw_code}/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yaml
- yq eval '.dependencies = {}' -i ${claw_code}/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yaml
+ yq eval '.dependencies = {}' -i "${claw_code}/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yaml"
+ yq eval '.dependencies = {}' -i "${claw_code}/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yaml"
fi
add_resource_if_set "GATEWAY" "${file}"
- if [[ "${mode}" != "dev" && "${enable_gw_lable}" == "true" ]]; then
+ if [[ "${mode}" != "dev" && "${enable_gw_lable}" == "true" ]]; then
# Automatically create nodeSelector and set gateway=enable
yq eval 'select(.kind == "Deployment").spec.template.spec.nodeSelector |= {"gateway": "enable"}' -i "${file}"
fi
- success "Gateway file generation completed: ${file}"
-}
-
-# 配置 JIUWENCLAW_ID,则生成 uuid4(供 Gateway 启动使用)
-ensure_jiuwenclaw_id() {
- if [ -n "${DEPLOY_VARS["JIUWENCLAW_ID"]:-}" ]; then
- info "JIUWENCLAW_ID already set, skip auto-generation"
- return
+ if [[ "${DEPLOY_VARS["APPLY_PATCH"]}" != "true" ]]; then
+ yq eval-all -i 'select(.kind != "Service" or .spec.type != "NodePort")' "${file}"
fi
- DEPLOY_VARS["JIUWENCLAW_ID"]="$(gen_uuid4)"
- success "Auto-generated JIUWENCLAW_ID=${DEPLOY_VARS["JIUWENCLAW_ID"]}"
+ success "Gateway file generation completed: ${file}"
}
-
render_gateway_files() {
local pvc_template_file="${CONFIG["CLAW_PVC_TEMPLATE_FILE"]}"
local pvc_file="${CONFIG["CLAW_PVC_FILE"]}"
@@ -116,7 +115,6 @@ render_gateway_files() {
fi
render_secret_configmap
- ensure_jiuwenclaw_id
gen_gateway_env_file
gen_gateway_config_file
@@ -124,15 +122,14 @@ render_gateway_files() {
render_config_template "${pvc_template_file}" "${pvc_file}" "DEPLOY_VARS"
fi
+ ensure_available_port "GATEWAY_CONFIG_HTTP_NODE_PORT"
gen_gateway_file
}
deploy_gateway() {
local namespace="${DEPLOY_VARS["NAMESPACE"]}"
- local envfile_name="${DEPLOY_VARS["GATEWAY_ENV_FILE_CM_NAME"]}"
- local env_file="${CONFIG["GATEWAY_ENV_FILE"]}"
- local conf_name="${DEPLOY_VARS["GATEWAY_CONFIG_MAP_NAME"]}"
- local conf_file="${CONFIG["GATEWAY_CONFIG_FILE"]}"
+ local env_yaml_file="${CONFIG["GATEWAY_ENV_YAML_FILE"]}"
+ local conf_yaml_file="${CONFIG["GATEWAY_CONFIG_YAML_FILE"]}"
local name="${DEPLOY_VARS["GATEWAY_NAME"]}"
local gateway_file="${CONFIG["GATEWAY_FILE"]}"
local pvc_file="${CONFIG["CLAW_PVC_FILE"]}"
@@ -141,26 +138,28 @@ deploy_gateway() {
ensure_secret_configmap
# 使用 apply 保证重复部署幂等:ConfigMap 已存在时更新内容,不因 create 冲突失败。
- exec_cmd kubectl apply -f ${CONFIG_DIR}/gateway-envfile.configmap.yaml
- exec_cmd kubectl apply -f ${CONFIG_DIR}/gateway-config.configmap.yaml
+ exec_cmd kubectl apply -f "${env_yaml_file}"
+ exec_cmd kubectl apply -f "${conf_yaml_file}"
if [[ "${mount_type}" == "pvc" && "${is_external_pvc}" == "false" ]]; then
- exec_cmd kubectl apply -f ${pvc_file}
+ exec_cmd kubectl apply -f "${pvc_file}"
fi
- exec_cmd kubectl apply -f ${gateway_file}
+ exec_cmd kubectl apply -f "${gateway_file}"
wait_k8s_resource_ready "deployment" "${name}" "${namespace}"
}
uninstall_gateway() {
local namespace="${DEPLOY_VARS["NAMESPACE"]}"
local gateway_name="${DEPLOY_VARS["GATEWAY_NAME"]}"
- local conf_name="${DEPLOY_VARS["GATEWAY_CONFIG_MAP_NAME"]}"
- local envfile_name="${DEPLOY_VARS["GATEWAY_ENV_FILE_CM_NAME"]}"
local gateway_file="${CONFIG["GATEWAY_FILE"]}"
local mount_type="${DEPLOY_VARS["CLAW_MOUNT_TYPE"]}"
+ local is_external_pvc="${DEPLOY_VARS["ENABLE_EXTERNAL_PVC"]}"
local pvc_file="${CONFIG["CLAW_PVC_FILE"]}"
+ local env_yaml_file="${CONFIG["GATEWAY_ENV_YAML_FILE"]}"
+ local conf_yaml_file="${CONFIG["GATEWAY_CONFIG_YAML_FILE"]}"
+
# 先优雅停 Pod,再清理周边资源
# gateway.yaml 含 ServiceAccount / Role / Deployment 等同文件资源。
# 不可 kubectl delete -f 一次性删掉:SA 被删后 Pod 仍在 Terminating 窗口内,
@@ -169,30 +168,14 @@ uninstall_gateway() {
exec_cmd kubectl delete deployment "${gateway_name}" -n "${namespace}" --ignore-not-found=true
wait_pod_terminated "${gateway_name}" "${namespace}"
- # 兜底清理 gateway 动态创建的 agentserver pod
- # 正常情况下 gateway 在 graceful shutdown 时会由 ServiceManager.stop()
- # -> cleanup_all_agentserver_pods 自行删除这些 pod;但 gateway 一旦在
- # terminationGracePeriodSeconds 内被 SIGKILL(例如 busy-loop 阻塞了 shutdown),
- # 这些 pod 会变成孤儿残留:agentserver pod 无 ownerReference,且不在本脚本的
- # 清理范围内(MODULES 不含 agentserver)。此处按 gateway 创建 pod 时打下的
- # 固定 label 兜底删除,保证 down 后无残留。
- local orphan_pods
- orphan_pods=$(kubectl get pods -n "${namespace}" -l jiuwenclaw-component=agentserver -o name 2>/dev/null || true)
- if [ -n "${orphan_pods}" ]; then
- info "Cleaning up orphan agentserver pods created by gateway (label: jiuwenclaw-component=agentserver)"
- exec_cmd kubectl delete pod -n "${namespace}" -l jiuwenclaw-component=agentserver --ignore-not-found=true
- else
- info "No orphan agentserver pods to clean up."
- fi
-
info "Deleting remaining Gateway resources (ServiceAccount, Role, Service, ...)"
exec_cmd kubectl delete -f "${gateway_file}" --ignore-not-found=true
- delete_k8s_resource "configmap" "${conf_name}" "${namespace}"
- delete_k8s_resource "configmap" "${envfile_name}" "${namespace}"
+ exec_cmd kubectl delete -f "${env_yaml_file}" --ignore-not-found=true
+ exec_cmd kubectl delete -f "${conf_yaml_file}" --ignore-not-found=true
- if [[ "${mount_type}" == "pvc" && -z "${DEPLOY_VARS["CLAW_PVC"]:-}" ]]; then
- exec_cmd kubectl delete -f ${pvc_file} --ignore-not-found=true
+ if [[ "${mount_type}" == "pvc" && "${is_external_pvc}" == "false" ]]; then
+ exec_cmd kubectl delete -f "${pvc_file}" --ignore-not-found=true
fi
uninstall_secret_configmap
- ensure_redis_down "runtime"
+ ensure_redis_down
}
diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.sh
index c7973da366..993f6244cf 100755
--- a/deploy/enterprise/global_vars.sh
+++ b/deploy/enterprise/global_vars.sh
@@ -41,9 +41,14 @@ declare -A CONFIG=(
["SECRET_CM_TEMPLATE_FILE"]="${TEMPLATE_DIR}/configmap-secret.template.yaml"
["SECRET_CM_FILE"]="${CONFIG_DIR}/configmap-secret.yaml"
+ ["GATEWAY_CONFIG_TEMPLATE_FILE"]="${TEMPLATE_DIR}/gateway-config.template.yaml"
["GATEWAY_CONFIG_FILE"]="${CONFIG_DIR}/gateway-config.yaml"
+ ["GATEWAY_CONFIG_YAML_FILE"]="${CONFIG_DIR}/gateway-config.configmap.yaml"
+
["GATEWAY_ENV_TEMPLATE_FILE"]="${TEMPLATE_DIR}/gateway.template.env"
["GATEWAY_ENV_FILE"]="${CONFIG_DIR}/gateway.env"
+ ["GATEWAY_ENV_YAML_FILE"]="${CONFIG_DIR}/gateway-env.configmap.yaml"
+
["GATEWAY_TEMPLATE_FILE"]="${TEMPLATE_DIR}/gateway.template.yaml"
["GATEWAY_FILE"]="${CONFIG_DIR}/gateway.yaml"
@@ -62,6 +67,12 @@ declare -A CONFIG=(
["IDENTITY_TEMPLATE_FILE"]="${TEMPLATE_DIR}/identity.template.yaml"
["IDENTITY_FILE"]="${CONFIG_DIR}/identity.yaml"
+ ["AS_JSON_TEMPLATE_FILE"]="${TEMPLATE_DIR}/agentserver.template.json"
+ ["AS_JSON_FILE"]="${CONFIG_DIR}/agentserver.json"
+ ["AS_ENV_TEMPLATE_FILE"]="${TEMPLATE_DIR}/agentserver.template.env"
+ ["AS_ENV_FILE"]="${CONFIG_DIR}/agentserver.env"
+ ["AS_ENV_YAML_FILE"]="${CONFIG_DIR}/agentserver-env.configmap.yaml"
+
["START_PORT"]="30000"
["END_PORT"]="32767"
@@ -97,12 +108,6 @@ declare -A DEPLOY_VARS=(
["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"
- ["AGENT_SERVER_SERVICE_CONCURRENCY"]="10"
- ["AGENT_SERVER_SESSION_CONCURRENCY"]="10"
- ["AGENT_SERVER_SESSION_TTL"]="60"
- ["AGENT_SERVER_REACT_MAX_ITER"]="10"
["CLAW_MOUNT_TYPE"]="pvc"
["CLAW_STORAGE_SIZE"]="1Gi"
["COLLECT_LOG_MASK_ENABLED"]="false"
@@ -120,12 +125,8 @@ declare -A DEPLOY_VARS=(
["ENABLE_EXTERNAL_RABBITMQ"]="false"
["ENABLE_EXTERNAL_REDIS"]="false"
["JIUWENSWARM_EDITION"]="enterprise"
- ["USER_WEB_MODE"]=""
- ["LOGIN_AUTH_SIMULATE"]="true"
- ["LOGIN_AUTH_SIMULATE_AVAILABLE"]="true"
["USER_WEB_IDP_TARGET"]=""
["USER_WEB_MANAGER_TARGET"]=""
- ["ENABLE_USER_WEB_EMBEDDING"]="false"
["FLUENT_BIT_NAME"]="fluent-bit"
["FLUENT_BIT_IMAGE"]="fluent/fluent-bit:3.0.0"
["FUNC_SVC_NAME"]="0@jiuwen@clawtest"
@@ -143,7 +144,6 @@ declare -A DEPLOY_VARS=(
["LOG_TO_FILE_ENABLED"]="true"
["GATEWAY_NAME"]="jiuwenclaw-gateway"
["GATEWAY_REPLICAS"]="1"
- ["GATEWAY_SQLITE_PATH"]="gateway.db"
["IS_UP_MANAGER_WEB"]="true"
["IDENTITY_NAME"]="jiuwenclaw-identity"
["IDENTITY_REST_PORT"]="8770"
@@ -233,6 +233,19 @@ declare -A DEPLOY_VARS=(
["AGENT_RUNTIME_LOG_LEVEL"]="INFO"
["WS_ALLOWED_ORIGINS"]=""
["WS_ORIGIN_CHECK_ENABLED"]="false"
+
+ ["AGENT_SERVER_HOME"]="/home/app"
+ ["AGENT_SERVER_NAME"]="jiuwenclaw-agentserver"
+ ["AGENT_SERVER_PORT"]="8766"
+ ["AGENT_SERVER_SERVICE_CONCURRENCY"]="10"
+ ["AGENT_SERVER_SESSION_CONCURRENCY"]="10"
+ ["AGENT_SERVER_SESSION_TTL"]="60"
+ ["AGENT_SERVER_REACT_MAX_ITER"]="10"
+ ["AGENT_SERVER_ENV_CM_NAME"]="jiuwenclaw-agentserver-env"
+ ["JIUWENBOX_NAME"]="jiuwenbox"
+ ["JIUWENBOX_PORT"]="8321"
+ ["JIUWENBOX_HOME"]="/home/app"
+ ["APPLY_PATCH"]="false"
)
declare -A OYR_COMPONENTS=(
diff --git a/deploy/enterprise/patch_handler.sh b/deploy/enterprise/patch_handler.sh
new file mode 100755
index 0000000000..a848792577
--- /dev/null
+++ b/deploy/enterprise/patch_handler.sh
@@ -0,0 +1,152 @@
+#!/usr/bin/env bash
+set -euo >/dev/null 2>&1
+
+render_patch_file() {
+ local namespace="${DEPLOY_VARS["NAMESPACE"]}"
+ local json_template="${CONFIG["AS_JSON_TEMPLATE_FILE"]}"
+ local json_file="${CONFIG["AS_JSON_FILE"]}"
+ local env_template="${CONFIG["AS_ENV_TEMPLATE_FILE"]}"
+ local env_file="${CONFIG["AS_ENV_FILE"]}"
+ local envfile_name="${DEPLOY_VARS["AGENT_SERVER_ENV_CM_NAME"]}"
+
+ info "Rendering AgentServer templates"
+ render_config_template "${json_template}" "${json_file}" "DEPLOY_VARS"
+ render_config_template "${env_template}" "${env_file}" "DEPLOY_VARS"
+
+ if ! jq . "${json_file}" >/dev/null 2>&1; then
+ error "AgentServer JSON rendering failed, invalid JSON format: ${json_file}"
+ fi
+
+ # product 模式:镜像内置代码,不需要 hostPath 挂载 / root 权限
+ # 三段式契约下:删 hostPath volumes + 主容器 securityContext + 引用已删卷的 volumeMounts
+ if [[ "${DEPLOY_VARS["MODE"]}" == "product" ]]; then
+ jq '.rawdata.templates[].volumes |= map(select(has("hostPath") | not))
+ | .rawdata.containers |= map(if .container_id == "c-agentserver" then del(.securityContext) else . end)' \
+ "${json_file}" > "${json_file}.tmp"
+ jq '(.rawdata.templates[0].volumes | map(.name)) as $keep
+ | .rawdata.containers[].volumeMounts |= map(select(.name as $n | $keep | map(. == $n) | any))' \
+ "${json_file}.tmp" > "${json_file}"
+ rm -f "${json_file}.tmp"
+ fi
+
+ # 移除所有注释行、过滤空值行 KEY=、按变量名排序
+ # 注意:不能 sort > 同一个文件,shell 会在管道启动前就截断输出文件,
+ # 导致左侧 grep 读到空。先写临时文件再 mv 覆盖。
+ grep -v '^[[:space:]]*#' "${env_file}" \
+ | grep '=' \
+ | awk -F'=' '$2 != ""' \
+ | sort > "${env_file}.tmp" && mv -f "${env_file}.tmp" "${env_file}"
+
+ kubectl create configmap -n "${namespace}" "${envfile_name}" \
+ --from-env-file="${env_file}" \
+ --dry-run=client -o yaml \
+ | yq eval 'del(.metadata.creationTimestamp)' > "${CONFIG["AS_ENV_YAML_FILE"]}"
+ success "AgentServer configuration rendered"
+}
+
+install_agentserver_patch() {
+ if [[ "${DEPLOY_VARS["RENDER_ONLY"]}" == "true" || "${DEPLOY_VARS["APPLY_PATCH"]}" == "false" ]]; then
+ return
+ fi
+
+ local runtime_port="${DEPLOY_VARS["AGENT_RUNTIME_NODE_PORT"]}"
+ local yaml_file="${CONFIG["AS_ENV_YAML_FILE"]}"
+ local json_file="${CONFIG["AS_JSON_FILE"]}"
+
+ ensure_secret_configmap
+ exec_cmd kubectl apply -f "${yaml_file}"
+
+ # 下发agentserver服务配置
+ info "Pushing AgentServer template"
+ set +e
+ local response=$(curl -s --max-time 20 -X POST "http://127.0.0.1:${runtime_port}/api/session/config_sync" \
+ -H "Content-Type: application/json" \
+ -d @"${json_file}" 2>&1)
+ local rc=$?
+ set -e
+
+ if [ ${rc} -ne 0 ]; then
+ error "Send AgentServer config failed (curl rc=${rc}): ${response}"
+ fi
+ success "AgentServer template pushed."
+}
+
+install_model_patch() {
+ if [[ "${DEPLOY_VARS["RENDER_ONLY"]}" == "true" || "${DEPLOY_VARS["APPLY_PATCH"]}" == "false" ]]; then
+ return
+ fi
+
+ local gw_node_port="${DEPLOY_VARS["GATEWAY_CONFIG_HTTP_NODE_PORT"]:-}"
+ local bot_id="${MODEL_BOT_ID:-default}"
+ local agent_template_id="${AGENT_TEMPLATE_ID:-default-agent}"
+ local model_template_id="default-model"
+
+ # 1. 下发 model_template(数据一:模型凭据)
+ info "Pushing model template (template_id=${model_template_id})"
+ set +e
+ local response=$(curl -s --max-time 20 -X POST "http://127.0.0.1:${gw_node_port}/api/v1/model-templates" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"template_id\":\"${model_template_id}\",
+ \"template_name\":\"${DEPLOY_VARS["MODEL_NAME"]} default\",
+ \"description\":\"auto-pushed\",
+ \"model_type\":[\"default\"],
+ \"api_base\":\"${DEPLOY_VARS["API_BASE"]}\",
+ \"api_key\":\"${DEPLOY_VARS["API_KEY"]}\",
+ \"model_id\":\"${DEPLOY_VARS["MODEL_NAME"]}\",
+ \"model_provider\":\"${DEPLOY_VARS["MODEL_PROVIDER"]}\",
+ \"timeout\":1800,
+ \"retry_count\":3,
+ \"enable_streaming\":true,
+ \"enable_function_calling\":true,
+ \"verify_ssl\":false,
+ \"enabled\":true
+ }" 2>&1)
+ local rc=$?
+ set -e
+ if [ ${rc} -ne 0 ]; then
+ error "Push model template failed (curl rc=${rc}): ${response}"
+ fi
+ success "Model template pushed (template_id=${model_template_id})"
+
+ # 2. 下发 agent_template(数据二:template_ref 指向 model_template)
+ info "Pushing agent template (template_id=${agent_template_id}, ref→${model_template_id})"
+ set +e
+ response=$(curl -s --max-time 20 -X POST "http://127.0.0.1:${gw_node_port}/api/v1/agent-templates" \
+ -H "Content-Type: application/json" \
+ -d "{\"template_id\":\"${agent_template_id}\",\"template_name\":\"default agent\",\"template_ref\":{\"default_model\":[\"${model_template_id}\"]},\"enabled\":true}" 2>&1)
+ rc=$?
+ set -e
+ if [ ${rc} -ne 0 ]; then
+ error "Push agent template failed (curl rc=${rc}): ${response}"
+ fi
+ success "Agent template pushed (template_id=${agent_template_id})"
+
+ # 3. 下发 instance_agent_resource(数据三:resource_id=bot_id, ref_template_id 指向 agent_template)
+ info "Pushing instance agent resource (resource_id=${bot_id}, ref→${agent_template_id})"
+ set +e
+ response=$(curl -s --max-time 20 -X POST "http://127.0.0.1:${gw_node_port}/api/v1/instance-agent-resources" \
+ -H "Content-Type: application/json" \
+ -d "{\"resource_id\":\"${bot_id}\",\"ref_template_id\":\"${agent_template_id}\",\"resource_name\":\"default agent\",\"match_expr\":[],\"enabled\":true}" 2>&1)
+ rc=$?
+ set -e
+ if [ ${rc} -ne 0 ]; then
+ error "Push instance agent resource failed (curl rc=${rc}): ${response}"
+ fi
+ success "Instance agent resource pushed (resource_id=${bot_id})"
+}
+
+install_patch()
+{
+ install_agentserver_patch
+ install_model_patch
+}
+
+uninstall_patch() {
+ if [[ "${DEPLOY_VARS["RENDER_ONLY"]}" == "true" || "${DEPLOY_VARS["APPLY_PATCH"]}" == "false" ]]; then
+ return
+ fi
+
+ local yaml_file="${CONFIG["AS_ENV_YAML_FILE"]}"
+ exec_cmd kubectl delete -f "${yaml_file}" --ignore-not-found=true
+}
\ No newline at end of file
diff --git a/deploy/enterprise/runtime_handler.sh b/deploy/enterprise/runtime_handler.sh
index d6dec19251..fa15fd3dea 100755
--- a/deploy/enterprise/runtime_handler.sh
+++ b/deploy/enterprise/runtime_handler.sh
@@ -5,9 +5,19 @@ gen_runtime_file() {
local template_file="${CONFIG["RUNTIME_TEMPLATE_FILE"]}"
local file="${CONFIG["RUNTIME_FILE"]}"
+ local redis_mode="${DEPLOY_VARS["REDIS_MODE"]}"
+ local redis_host="${DEPLOY_VARS["REDIS_HOST"]}"
+ local redis_port="${DEPLOY_VARS["REDIS_PORT"]}"
+ local redis_db="${DEPLOY_VARS["AGENT_RUNTIME_REDIS_DB"]}"
+
+ if [[ "${redis_mode}" == "cluster" ]]; then
+ DEPLOY_VARS["OPENJIUWEN_SERVICE_REDIS_URL"]="redis+cluster://${redis_host}:${redis_port}"
+ else
+ DEPLOY_VARS["OPENJIUWEN_SERVICE_REDIS_URL"]="redis://${redis_host}:${redis_port}/${redis_db}"
+ fi
+
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 += [
@@ -19,11 +29,16 @@ gen_runtime_file() {
fi
add_resource_if_set "RUNTIME" "${file}"
+ if [[ "${DEPLOY_VARS["APPLY_PATCH"]}" != "true" ]]; then
+ yq eval-all -i 'select(.kind != "Service" or .spec.type != "NodePort")' "${file}"
+ fi
}
render_runtime_files() {
render_secret_configmap
+ ensure_available_port "AGENT_RUNTIME_NODE_PORT"
gen_runtime_file
+ render_patch_file
}
deploy_runtime() {
@@ -34,6 +49,7 @@ deploy_runtime() {
ensure_secret_configmap
exec_cmd kubectl apply -f ${file}
wait_k8s_resource_ready "deployment" "${name}" "${namespace}"
+ install_patch
}
uninstall_runtime() {
@@ -62,5 +78,6 @@ uninstall_runtime() {
info "Deleting remaining Runtime resources (ServiceAccount, Role, Service, ...)"
exec_cmd kubectl delete -f "${file}" --ignore-not-found=true
uninstall_secret_configmap
- ensure_redis_down "gateway"
+ ensure_redis_down
+ uninstall_patch
}
diff --git a/deploy/enterprise/templates/.env.custom.template b/deploy/enterprise/templates/.env.custom.template
index 3bcf981245..d5399c8793 100644
--- a/deploy/enterprise/templates/.env.custom.template
+++ b/deploy/enterprise/templates/.env.custom.template
@@ -16,22 +16,9 @@ MANAGER_WEB_IMAGE="<<MANAGER_WEB_IMAGE>>"
IDENTITY_IMAGE="<<IDENTITY_IMAGE>>"
JIUWENBOX_IMAGE="<<JIUWENBOX_IMAGE>>"
-JIUWENSWARM_EDITION="enterprise"
-# Gateway / User Web 产品形态:personal | enterprise
GATEWAY_SESSION_MAP_SCOPE="per_chat_bot_user"
JIUWENBOX_ENABLED=true
-# 是否启动 Manager Web;JIUWENSWARM_EDITION=enterprise 时 up 会默认带上 manager
-IS_UP_MANAGER_WEB=true
-
-# 联合认证 Demo Provider(仅用于部署联调,默认关闭)
-IDENTITY_FEDERATION_DEMO_ENABLED=false
-IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX=/idp
-IDENTITY_FEDERATION_REQUEST_TTL=300
-IDENTITY_FEDERATION_CODE_TTL=60
-IDENTITY_FEDERATION_DEMO_ADMIN_GROUP=enterprise-admins
-
-
# 设置空闲端口,请确保该端口的唯一性(范围: 30000-32767)
MYSQL_NODE_PORT="<<MYSQL_NODE_PORT>>"
POSTGRESQL_NODE_PORT="<<POSTGRESQL_NODE_PORT>>"
diff --git a/deploy/enterprise/templates/agentserver.template.env b/deploy/enterprise/templates/agentserver.template.env
new file mode 100644
index 0000000000..abdf9b45f1
--- /dev/null
+++ b/deploy/enterprise/templates/agentserver.template.env
@@ -0,0 +1,33 @@
+# AgentServer HTTP/SSE 入口
+AGENT_SERVER_HOST=0.0.0.0
+AGENT_HTTP_ENABLED=true
+AGENT_HTTP_HOST=0.0.0.0
+AGENT_HTTP_PORT=8766
+
+# 基础配置
+TZ=<<TIMEZONE>>
+HOME=<<AGENT_SERVER_HOME>>
+LOG_ROOT_PATH=<<AGENT_SERVER_HOME>>
+JIUWENSWARM_EDITION=enterprise
+
+# 数据库信息
+GATEWAY_DB_TYPE=<<DB_TYPE>>
+GATEWAY_DB_HOST=<<DB_HOST>>
+GATEWAY_DB_PORT=<<DB_PORT>>
+GATEWAY_DB_USER=<<GATEWAY_DB_USER>>
+GATEWAY_DB_NAME=<<GATEWAY_DB_NAME>>
+GATEWAY_PG_SCHEMA=<<GATEWAY_PG_SCHEMA>>
+
+
+# 日志
+LLM_SSL_VERIFY=False
+LOG_MASK_ENABLED=false
+LOG_TO_FILE_ENABLED=true
+
+# 沙箱配置
+JIUWENCLAW_SANDBOX_ENABLED=true
+JIUWENCLAW_SANDBOX_URL=http://127.0.0.1:<<JIUWENBOX_PORT>>
+JIUWENCLAW_SANDBOX_TYPE=jiuwenbox
+JIUWENCLAW_SANDBOX_STARTUP_MODE=external
+JIUWENCLAW_SANDBOX_PRESERVE_FILE_SHARING_MODE=mount
+JIUWENBOX_FALLBACK_ON_FAILURE=False
diff --git a/deploy/enterprise/templates/agentserver.template.json b/deploy/enterprise/templates/agentserver.template.json
new file mode 100644
index 0000000000..28559bf291
--- /dev/null
+++ b/deploy/enterprise/templates/agentserver.template.json
@@ -0,0 +1,224 @@
+{
+ "type": "config_sync",
+ "metadata": {
+ "request_id": "default",
+ "session_id": null,
+ "user_id": "default",
+ "bot_id": "default",
+ "extra": {
+ "group_id": "default"
+ }
+ },
+ "rawdata": {
+ "containers": [
+ {
+ "container_id": "c-agentserver",
+ "name": "<<AGENT_SERVER_NAME>>",
+ "image": "<<AGENT_SERVER_IMAGE>>",
+ "imagePullPolicy": "IfNotPresent",
+ "ports": [
+ {
+ "name": "sse",
+ "containerPort": <<AGENT_SERVER_PORT>>
+ }
+ ],
+ "envFrom": [
+ {
+ "secretRef": {
+ "name": "<<SECRET_CM_NAME>>"
+ }
+ },
+ {
+ "configMapRef": {
+ "name": "<<AGENT_SERVER_ENV_CM_NAME>>"
+ }
+ }
+ ],
+ "securityContext": {
+ "runAsUser": 0,
+ "runAsGroup": 0
+ },
+ "readinessProbe": {
+ "httpGet": {
+ "path": "/api/v1/health",
+ "port": <<AGENT_SERVER_PORT>>
+ },
+ "initialDelaySeconds": 5,
+ "periodSeconds": 10
+ },
+ "volumeMounts": [
+ {
+ "name": "hp-code",
+ "mountPath": "/app/jiuwenswarm"
+ },
+ {
+ "name": "hp-rt-foundation",
+ "mountPath": "/usr/local/lib/python3.11/site-packages/openjiuwen_runtime/foundation"
+ },
+ {
+ "name": "hp-rt-management",
+ "mountPath": "/usr/local/lib/python3.11/site-packages/openjiuwen_runtime/management"
+ },
+ {
+ "name": "hp-openjiuwen",
+ "mountPath": "/usr/local/lib/python3.11/site-packages/openjiuwen"
+ },
+ {
+ "name": "gw-envfile",
+ "mountPath": "/root/.jiuwenswarm/config/.env",
+ "subPath": ".env"
+ },
+ {
+ "name": "data",
+ "mountPath": "<<AGENT_SERVER_HOME>>/.jiuwenswarm"
+ }
+ ]
+ },
+ {
+ "container_id": "c-jiuwenbox",
+ "name": "<<JIUWENBOX_NAME>>",
+ "image": "<<JIUWENBOX_IMAGE>>",
+ "imagePullPolicy": "IfNotPresent",
+ "ports": [
+ {
+ "containerPort": <<JIUWENBOX_PORT>>
+ }
+ ],
+ "env": [
+ {
+ "name": "JIUWENBOX_LISTEN",
+ "value": "http://0.0.0.0:<<JIUWENBOX_PORT>>"
+ },
+ {
+ "name": "JIUWENBOX_POLICY_PATH",
+ "value": "/usr/local/lib/python3.11/site-packages/jiuwenbox/configs/enterprise-policy.yaml"
+ },
+ {
+ "name": "TZ",
+ "value": "<<TIMEZONE>>"
+ }
+ ],
+ "securityContext": {
+ "privileged": true,
+ "capabilities": {
+ "add": [
+ "SYS_ADMIN",
+ "NET_ADMIN"
+ ]
+ },
+ "seccompProfile": {
+ "type": "Unconfined"
+ },
+ "appArmorProfile": {
+ "type": "Unconfined"
+ }
+ },
+ "readinessProbe": {
+ "tcpSocket": {
+ "port": <<JIUWENBOX_PORT>>
+ },
+ "initialDelaySeconds": 10,
+ "periodSeconds": 5
+ },
+ "volumeMounts": [
+ {
+ "name": "hp-cgroup",
+ "mountPath": "/sys/fs/cgroup"
+ },
+ {
+ "name": "hp-jiuwenbox",
+ "mountPath": "/usr/local/lib/python3.11/site-packages/jiuwenbox"
+ },
+ {
+ "name": "data",
+ "mountPath": "<<JIUWENBOX_HOME>>/.jiuwenswarm"
+ }
+ ]
+ }
+ ],
+ "templates": [
+ {
+ "template_id": "default",
+ "template_name": "default",
+ "main_container_id": "c-agentserver",
+ "sidecar_container_ids": [
+ "c-jiuwenbox"
+ ],
+ "pod_name": "<<AGENT_SERVER_NAME>>",
+ "namespace": "<<NAMESPACE>>",
+ "nodeName": "<<CURRENT_NODE_NAME>>",
+ "sse_path": "/api/v1/events/stream",
+ "scope_concurrency": 3,
+ "pod_concurrency": 2,
+ "session_ttl": 60,
+ "pod_ttl": 3600,
+ "min_idle_pods": 1,
+ "ready_timeout": 240,
+ "volumes": [
+ {
+ "name": "hp-code",
+ "hostPath": {
+ "path": "<<CLAW_CODE_PATH>>",
+ "type": "Directory"
+ }
+ },
+ {
+ "name": "hp-rt-foundation",
+ "hostPath": {
+ "path": "<<RUNTIME_CODE_PATH>>/foundation/openjiuwen_runtime/foundation",
+ "type": "Directory"
+ }
+ },
+ {
+ "name": "hp-rt-management",
+ "hostPath": {
+ "path": "<<RUNTIME_CODE_PATH>>/management/openjiuwen_runtime/management",
+ "type": "Directory"
+ }
+ },
+ {
+ "name": "hp-openjiuwen",
+ "hostPath": {
+ "path": "<<CORE_CODE_PATH>>/openjiuwen",
+ "type": "Directory"
+ }
+ },
+ {
+ "name": "gw-envfile",
+ "configMap": {
+ "name": "<<GATEWAY_ENV_FILE_CM_NAME>>"
+ }
+ },
+ {
+ "name": "data",
+ "persistentVolumeClaim": {
+ "claimName": "<<CLAW_PVC>>"
+ }
+ },
+ {
+ "name": "hp-cgroup",
+ "hostPath": {
+ "path": "/sys/fs/cgroup",
+ "type": "Directory"
+ }
+ },
+ {
+ "name": "hp-jiuwenbox",
+ "hostPath": {
+ "path": "<<CLAW_CODE_PATH>>/jiuwenbox/src/jiuwenbox",
+ "type": "Directory"
+ }
+ }
+ ]
+ }
+ ],
+ "scopes": [
+ {
+ "scope_id": "default",
+ "index": 100,
+ "template_id": "default",
+ "routing_rules": ""
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/deploy/enterprise/templates/gateway.template.env b/deploy/enterprise/templates/gateway.template.env
index b2ec03f7f6..8ed4107ac9 100644
--- a/deploy/enterprise/templates/gateway.template.env
+++ b/deploy/enterprise/templates/gateway.template.env
@@ -15,7 +15,7 @@ FETCH_WEBPAGE_TOTAL_TIMEOUT=<<FETCH_WEBPAGE_TOTAL_TIMEOUT>>
# Runtime Orchestrator Configuration
AGENT_SERVER_IMAGE=<<AGENT_SERVER_IMAGE>>
AGENT_SERVER_PORT=18092
-AGENT_SERVER_CONTAINER_NAME=<<AGENT_SERVER_POD_NAME>>
+AGENT_SERVER_CONTAINER_NAME=<<AGENT_SERVER_NAME>>
AGENT_SERVER_PORT_NAME=http1
AGENT_SERVER_IMAGE_PULL_POLICY=IfNotPresent
AGENT_SERVER_CUSTOM_ENVS=<<AGENT_SERVER_CUSTOM_ENVS>>
@@ -84,7 +84,6 @@ API_BASE=<<API_BASE>>
LLM_SSL_VERIFY=False
# Gateway Configuration
-JIUWENCLAW_ID=<<JIUWENCLAW_ID>>
LOG_MASK_ENABLED=<<LOG_MASK_ENABLED>>
LOG_TO_FILE_ENABLED=<<LOG_TO_FILE_ENABLED>>
HEARTBEAT_ENABLED=FALSE
diff --git a/deploy/enterprise/templates/gateway.template.yaml b/deploy/enterprise/templates/gateway.template.yaml
index daa0e89b0a..6b16d3a794 100644
--- a/deploy/enterprise/templates/gateway.template.yaml
+++ b/deploy/enterprise/templates/gateway.template.yaml
@@ -169,3 +169,20 @@ spec:
port: <<GATEWAY_CONFIG_HTTP_PORT>>
targetPort: <<GATEWAY_CONFIG_HTTP_PORT>>
type: ClusterIP # 集群内部访问,不需要外网
+
+---
+# NodePort Service:供外连接, 只暴露 config-http 端口
+apiVersion: v1
+kind: Service
+metadata:
+ name: <<GATEWAY_NAME>>-nodeport
+ namespace: <<NAMESPACE>>
+spec:
+ type: NodePort
+ ports:
+ - name: config-http
+ port: <<GATEWAY_CONFIG_HTTP_PORT>>
+ targetPort: <<GATEWAY_CONFIG_HTTP_PORT>>
+ nodePort: <<GATEWAY_CONFIG_HTTP_NODE_PORT>>
+ selector:
+ app: <<GATEWAY_NAME>>
diff --git a/deploy/enterprise/templates/manager-web.template.yaml b/deploy/enterprise/templates/manager-web.template.yaml
index 2be8e507da..7fa0a63118 100644
--- a/deploy/enterprise/templates/manager-web.template.yaml
+++ b/deploy/enterprise/templates/manager-web.template.yaml
@@ -28,7 +28,6 @@ spec:
value: "0.0.0.0"
- name: MANAGER_WEB_PORT
value: "<<MANAGER_WEB_PORT>>"
- # 浏览器只能访问 Manager Web 同源路径,不能暴露 Kubernetes 内部 DNS。
- name: VITE_API_BASE
value: "/api"
- name: VITE_IDP_BASE
@@ -47,7 +46,7 @@ spec:
value: "<<TIMEZONE>>"
---
-# NodePort Service:供外连接 Manager Web UI
+# NodePort Service:供外连接
apiVersion: v1
kind: Service
metadata:
diff --git a/deploy/enterprise/templates/runtime.template.yaml b/deploy/enterprise/templates/runtime.template.yaml
index e076e72be9..143308673a 100644
--- a/deploy/enterprise/templates/runtime.template.yaml
+++ b/deploy/enterprise/templates/runtime.template.yaml
@@ -143,7 +143,7 @@ spec:
value: "<<TIMEZONE>>"
---
-# Service:ClusterIP(gateway / 其它服务经此访问 agent-runtime)
+# 集群内部访问: 提供稳定 DNS 域名
apiVersion: v1
kind: Service
metadata:
@@ -157,3 +157,19 @@ spec:
port: <<AGENT_RUNTIME_PORT>>
targetPort: <<AGENT_RUNTIME_PORT>>
type: ClusterIP
+
+---
+# NodePort Service:供外连接
+apiVersion: v1
+kind: Service
+metadata:
+ name: <<AGENT_RUNTIME_NAME>>-nodeport
+ namespace: <<NAMESPACE>>
+spec:
+ type: NodePort
+ ports:
+ - port: <<AGENT_RUNTIME_PORT>>
+ targetPort: <<AGENT_RUNTIME_PORT>>
+ nodePort: <<AGENT_RUNTIME_NODE_PORT>>
+ selector:
+ app: <<AGENT_RUNTIME_NAME>>
diff --git a/deploy/enterprise/templates/web.template.yaml b/deploy/enterprise/templates/web.template.yaml
index a652690ea3..47aee37973 100644
--- a/deploy/enterprise/templates/web.template.yaml
+++ b/deploy/enterprise/templates/web.template.yaml
@@ -36,23 +36,11 @@ spec:
value: "0.0.0.0"
- name: JIUWENSWARM_EDITION
value: "<<JIUWENSWARM_EDITION>>"
- - name: VITE_JIUWENSWARM_EDITION
- value: "<<JIUWENSWARM_EDITION>>"
- name: LOGIN_AUTH_SIMULATE
- value: "<<LOGIN_AUTH_SIMULATE>>"
- - name: VITE_LOGIN_AUTH_SIMULATE
- value: "<<LOGIN_AUTH_SIMULATE>>"
- - name: LOGIN_AUTH_SIMULATE_AVAILABLE
- value: "<<LOGIN_AUTH_SIMULATE_AVAILABLE>>"
- - name: VITE_LOGIN_AUTH_SIMULATE_AVAILABLE
- value: "<<LOGIN_AUTH_SIMULATE_AVAILABLE>>"
- - name: USER_WEB_IDP_TARGET
- value: "<<USER_WEB_IDP_TARGET>>"
- - name: USER_WEB_MANAGER_TARGET
- value: "<<USER_WEB_MANAGER_TARGET>>"
+ value: "<<APPLY_PATCH>>"
- name: FRONTEND_PORT
value: "<<WEB_HTTP_PORT>>"
- - name: VITE_WEB_TRANSPORT
+ - name: WEB_TRANSPORT
value: "http"
- name: ENTERPRISE_WEB_WS_HOST
value: "0.0.0.0"
diff --git a/deploy/enterprise/tests/test_identity_user_web_deploy.sh b/deploy/enterprise/tests/test_identity_user_web_deploy.sh
deleted file mode 100755
index fbcbc4636c..0000000000
--- a/deploy/enterprise/tests/test_identity_user_web_deploy.sh
+++ /dev/null
@@ -1,217 +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}/args_handler.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"
-
- MODULES=()
- process_modules
- assert_equal "GATEWAY WEB MANAGER RUNTIME" "${MODULES[*]}" "enterprise default must include Manager"
- MODULES=()
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="personal"
- process_modules
- assert_equal "GATEWAY WEB RUNTIME" "${MODULES[*]}" "personal default must exclude Manager"
- MODULES=()
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="enterprise"
-
- 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 \
- "enterprise" \
- "${DEPLOY_VARS["JIUWENSWARM_EDITION"]}" \
- "JIUWENSWARM_EDITION must default to enterprise"
- printf '%s\n' 'JIUWENSWARM_EDITION=personal' > "${test_dir}/.env.custom"
- read_env_from_file "${test_dir}/.env.custom" "DEPLOY_VARS"
- assert_equal \
- "personal" \
- "${DEPLOY_VARS["JIUWENSWARM_EDITION"]}" \
- ".env.custom edition value must override the default"
-
- CONFIG["WEB_FILE"]="${test_dir}/web.yaml"
-
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="personal"
- 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"
- assert_equal \
- "personal" \
- "$(yq eval-all 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "JIUWENSWARM_EDITION").value' "${CONFIG["WEB_FILE"]}")" \
- "personal mode must inject JIUWENSWARM_EDITION"
-
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="enterprise"
- gen_web_file
- assert_equal \
- "NodePort" \
- "$(yq eval-all 'select(.metadata.name == "jiuwenclaw-web-nodeport") | .spec.type' "${CONFIG["WEB_FILE"]}")" \
- "enterprise mode must expose the independent User Web NodePort"
- assert_equal \
- "enterprise" \
- "$(yq eval-all 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "JIUWENSWARM_EDITION").value' "${CONFIG["WEB_FILE"]}")" \
- "enterprise mode must inject JIUWENSWARM_EDITION"
- assert_equal \
- "enterprise" \
- "$(yq eval-all 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "VITE_JIUWENSWARM_EDITION").value' "${CONFIG["WEB_FILE"]}")" \
- "enterprise mode must inject VITE_JIUWENSWARM_EDITION"
-
- DEPLOY_VARS["IS_UP_MANAGER_WEB"]="false"
- DEPLOY_VARS["USER_WEB_IDP_TARGET"]="http://jiuwenclaw-identity:8770"
- DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]="http://jiuwenclaw-manager-server:8765"
- check_jiuwenswarm_edition_config
-
- DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"
- DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="true"
- check_jiuwenswarm_edition_config
-
- DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="invalid"
- if check_jiuwenswarm_edition_config >/dev/null 2>&1; then
- echo "FAIL: invalid LOGIN_AUTH_SIMULATE value must be rejected" >&2
- exit 1
- fi
- DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="false"
- check_jiuwenswarm_edition_config
-
- DEPLOY_VARS["JIUWENSWARM_EDITION"]="invalid"
- if (check_jiuwenswarm_edition_config) >/dev/null 2>&1; then
- echo "FAIL: invalid edition 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["JIUWENSWARM_EDITION"]="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/update_conf.sh b/deploy/enterprise/update_conf.sh
index 6ca9a5395f..4283996167 100755
--- a/deploy/enterprise/update_conf.sh
+++ b/deploy/enterprise/update_conf.sh
@@ -8,8 +8,7 @@ rm -f "${DEST_FILE}"
cp -f "${SRC_FILE}" "${DEST_FILE}"
yq eval '.gateway.agent_client.type = "jiuwen"' -i "${DEST_FILE}"
-JIUWENSWARM_EDITION="${JIUWENSWARM_EDITION:-enterprise}" \
- yq eval '.gateway.edition = strenv(JIUWENSWARM_EDITION)' -i "${DEST_FILE}"
+yq eval '.gateway.edition = "enterprise"' -i "${DEST_FILE}"
yq eval '.gateway.session_map_scope = "<<GATEWAY_SESSION_MAP_SCOPE>>"' -i "${DEST_FILE}"
yq eval '.channels.feishu = {}' -i "${DEST_FILE}"
yq eval '.react.max_iterations = "<<AGENT_SERVER_REACT_MAX_ITER>>"' -i "${DEST_FILE}"
diff --git a/deploy/enterprise/web_handler.sh b/deploy/enterprise/web_handler.sh
index e70530e16d..a01398b638 100755
--- a/deploy/enterprise/web_handler.sh
+++ b/deploy/enterprise/web_handler.sh
@@ -51,6 +51,20 @@ gen_web_file() {
]' -i "${file}"
fi
+ if [[ "${DEPLOY_VARS["APPLY_PATCH"]}" == "false" ]]; then
+ yq eval '
+ select(.kind == "Deployment").spec.template.spec.containers[0].env += [
+ {
+ "name": "USER_WEB_IDP_TARGET",
+ "value": "'"${DEPLOY_VARS["USER_WEB_IDP_TARGET"]}"'"
+ },
+ {
+ "name": "USER_WEB_MANAGER_TARGET",
+ "value": "'"${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]}"'"
+ }
+ ]' -i "${file}"
+ fi
+
add_resource_if_set "WEB" "${file}"
# yq 追加资源配置时可能重复 env;Deployment strategic merge patch 不接受重复键,
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index c846dcc171..a99900abee 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -72,7 +72,7 @@ def _default_dist_dir() -> Path:
def _inject_user_web_runtime_config(
document: str,
login_auth_simulate: bool = True,
- login_auth_simulate_available: bool = True,
+ web_transport: str = "websocket",
) -> str:
"""Inject runtime edition and login-auth flags into index.html."""
edition = "enterprise" if is_enterprise() else "personal"
@@ -82,10 +82,7 @@ def _inject_user_web_runtime_config(
"__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__",
"true" if login_auth_simulate else "false",
)
- .replace(
- "__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__",
- "true" if login_auth_simulate_available else "false",
- )
+ .replace("__JIUWEN_WEB_TRANSPORT_VALUE__", web_transport)
)
@@ -100,6 +97,13 @@ def _parse_login_auth_simulate(raw: str | None) -> bool:
)
+def _parse_web_transport(raw: str | None) -> str:
+ value = (raw or "").strip().lower()
+ if value in ("http", "a2"):
+ return "http"
+ return "websocket"
+
+
def _probe_http_service(
target: str, path: str, service_name: str, timeout: float = 3.0
) -> tuple[bool, str]:
@@ -155,7 +159,7 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
manager_api_target = ""
ws_disable_compress = False
login_auth_simulate = True
- login_auth_simulate_available = True
+ web_transport = "websocket"
logger = logging.getLogger(__name__)
_HOP_BY_HOP_HEADERS = {
@@ -688,7 +692,7 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
body = _inject_user_web_runtime_config(
index.read_text(encoding="utf-8"),
self.login_auth_simulate,
- self.login_auth_simulate_available,
+ self.web_transport,
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
@@ -921,23 +925,15 @@ def main() -> None:
_ConfiguredHandler.manager_api_target = os.getenv("USER_WEB_MANAGER_TARGET", "").strip()
enterprise = is_enterprise()
login_auth_simulate_raw = os.getenv("LOGIN_AUTH_SIMULATE")
- login_auth_simulate_available_raw = os.getenv("LOGIN_AUTH_SIMULATE_AVAILABLE")
try:
login_auth_simulate = _parse_login_auth_simulate(
login_auth_simulate_raw
)
- login_auth_simulate_available = _parse_login_auth_simulate(
- login_auth_simulate_available_raw
- )
except ValueError as exc:
raise SystemExit(str(exc)) from exc
_ConfiguredHandler.login_auth_simulate = login_auth_simulate
- _ConfiguredHandler.login_auth_simulate_available = login_auth_simulate_available
- if enterprise and login_auth_simulate and not login_auth_simulate_available:
- raise SystemExit(
- "配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;"
- "请设置 LOGIN_AUTH_SIMULATE=false 并接入 manager ID认证服务"
- )
+ web_transport = _parse_web_transport(os.getenv("WEB_TRANSPORT"))
+ _ConfiguredHandler.web_transport = web_transport
_ConfiguredHandler.web_http_target = web_http_target
_ConfiguredHandler.ws_disable_compress = args.ws_disable_compress
_ConfiguredHandler.logger = logger
diff --git a/jiuwenswarm/channels/web/frontend/index.html b/jiuwenswarm/channels/web/frontend/index.html
index 15b119c011..fef59259b1 100644
--- a/jiuwenswarm/channels/web/frontend/index.html
+++ b/jiuwenswarm/channels/web/frontend/index.html
@@ -13,7 +13,7 @@
<script>
window.__JIUWENSWARM_EDITION__ = '__JIUWENSWARM_EDITION_VALUE__';
window.__JIUWEN_LOGIN_AUTH_SIMULATE__ = '__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__';
- window.__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__ = '__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__';
+ window.__JIUWEN_WEB_TRANSPORT__ = '__JIUWEN_WEB_TRANSPORT_VALUE__';
</script>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 8d3f9cc378..68d09a0c71 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -8,7 +8,7 @@
"prebuild": "cd ../../../.. && node ./jiuwenswarm/scripts/generate-agent-folders.js",
"dev": "vite",
"build": "tsc && vite build",
- "build:customer": "tsc && INCLUDE_LOGIN_AUTH_SIMULATE=false VITE_LOGIN_AUTH_SIMULATE_AVAILABLE=false VITE_LOGIN_AUTH_SIMULATE=false vite build",
+ "build:customer": "tsc && VITE_LOGIN_AUTH_SIMULATE=false vite build",
"test:code-turn-diff-binding": "tsc src/features/code-mode/codeTurnDiffBinding.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/code-turn-diff-binding --skipLibCheck --noEmitOnError && node --test tests/codeTurnDiffBinding.test.mjs",
"test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs",
"test:spreadsheet-preview": "esbuild src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts src/components/ArtifactsPanel/spreadsheetPreviewModel.ts src/components/ArtifactsPanel/filePreviewModel.ts src/components/ArtifactsPanel/chartGeometry.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/spreadsheet-preview && node --test tests/spreadsheetPreview.test.mjs",
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
index 747a1af28b..9e5858c018 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
@@ -3,13 +3,13 @@ import { parseRuntimeScope } from '../../services/runtimeScope';
import type { EnterpriseAuthProvider } from '../types';
const DEFAULTS = {
- userId: 'debug-user',
+ userId: 'default',
displayName: 'Debug User',
- groupId: 'debug-group',
+ groupId: 'default',
groupName: 'Debug Organization',
gatewayId: 'debug-gateway',
gatewayName: 'Debug Gateway',
- botId: 'debug-agent',
+ botId: 'default',
botName: 'Debug Agent',
} as const;
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts
deleted file mode 100644
index 5363244ae5..0000000000
--- a/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import type { EnterpriseAuthProvider } from './types';
-
-// Customer builds bind the virtual simulation provider to this empty adapter.
-// This keeps the registry stable while allowing auth/simulate/ to be omitted.
-export const simulatedAuthProvider: EnterpriseAuthProvider | null = null;
diff --git a/jiuwenswarm/channels/web/frontend/src/utils/env.ts b/jiuwenswarm/channels/web/frontend/src/utils/env.ts
index c092c33a5f..7346af0178 100644
--- a/jiuwenswarm/channels/web/frontend/src/utils/env.ts
+++ b/jiuwenswarm/channels/web/frontend/src/utils/env.ts
@@ -23,8 +23,15 @@ export function getWsBase(): string {
export type WebTransport = "websocket" | "http";
-/** 构建期选定,运行时不探测。默认 websocket。`a2` 与 `http` 同义。 */
+/** 运行时由 app_web.py 注入 window.__JIUWEN_WEB_TRANSPORT__;未注入回退构建期值。默认 websocket。`a2` 与 `http` 同义。 */
export function getWebTransport(): WebTransport {
+ const injected = String(window.__JIUWEN_WEB_TRANSPORT__ ?? "").trim().toLowerCase();
+ if (injected && !injected.startsWith("__")) {
+ if (injected === "http" || injected === "a2") {
+ return "http";
+ }
+ return "websocket";
+ }
const raw = String(
import.meta.env.VITE_WEB_TRANSPORT ?? import.meta.env.VITE_TRANSPORT ?? "websocket"
)
diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
index 438ab0ee6c..ba193abe3e 100644
--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
@@ -10,7 +10,6 @@ interface ImportMetaEnv {
readonly VITE_WEB_HTTP_BASE?: string;
readonly VITE_JIUWENSWARM_EDITION?: string;
readonly VITE_LOGIN_AUTH_SIMULATE?: string;
- readonly VITE_LOGIN_AUTH_SIMULATE_AVAILABLE?: string;
}
interface ImportMeta {
@@ -51,8 +50,8 @@ interface Window {
__JIUWENSWARM_EDITION__?: string;
/** Login simulation switch injected by the User Web server. */
__JIUWEN_LOGIN_AUTH_SIMULATE__?: boolean | string;
- /** Whether this frontend artifact contains the optional simulation plugin. */
- __JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__?: boolean | string;
+ /** Web transport mode injected by the User Web server (websocket | http). */
+ __JIUWEN_WEB_TRANSPORT__?: string;
}
declare module 'virtual:login-auth-simulate-provider' {
diff --git a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
index c3f18aec59..c181c6eb5a 100644
--- a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
@@ -74,10 +74,10 @@ test('simulated enterprise login uses local defaults without an access token', (
resetBrowserState();
const context = buildSimulatedEnterpriseContext('');
- assert.equal(context.user.user_id, 'debug-user');
- assert.equal(context.org.group_id, 'debug-group');
+ assert.equal(context.user.user_id, 'default');
+ assert.equal(context.org.group_id, 'default');
assert.equal(context.gateway.jiuwenclaw_id, 'debug-gateway');
- assert.equal(context.selectedBot, 'debug-agent');
+ assert.equal(context.selectedBot, 'default');
assert.doesNotMatch(renderEntry('enterprise', true), /正在前往登录页/);
});
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 23dd757e89..0896bdf262 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -329,10 +329,6 @@ function parseLoginAuthSimulate(raw: string | undefined): boolean {
)
}
-const loginAuthSimulateIncluded = parseLoginAuthSimulate(
- process.env.INCLUDE_LOGIN_AUTH_SIMULATE ?? process.env.VITE_LOGIN_AUTH_SIMULATE_AVAILABLE
-)
-
/** Mirrors ``jiuwenswarm.common.local_env_config.is_enterprise`` for Vite startup checks. */
function isEnterpriseEdition(): boolean {
const edition = (process.env.JIUWENSWARM_EDITION ?? process.env.VITE_JIUWENSWARM_EDITION ?? '')
@@ -346,13 +342,6 @@ function loginAuthStartupCheck(): Plugin {
const simulateRaw = process.env.LOGIN_AUTH_SIMULATE ?? process.env.VITE_LOGIN_AUTH_SIMULATE
const simulate = parseLoginAuthSimulate(simulateRaw)
- if (enterprise && simulate && !loginAuthSimulateIncluded) {
- throw new Error(
- '配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;' +
- '请设置 LOGIN_AUTH_SIMULATE=false 并接入 manager ID认证服务'
- )
- }
-
return {
name: 'login-auth-startup-check',
async configureServer() {
@@ -431,9 +420,7 @@ export default defineConfig({
'@': path.resolve(__dirname, './src'),
'virtual:login-auth-simulate-provider': path.resolve(
__dirname,
- loginAuthSimulateIncluded
- ? './src/auth/simulate/available.ts'
- : './src/auth/simulateUnavailable.ts'
+ './src/auth/simulate/available.ts',
),
},
},
diff --git a/jiuwenswarm/gateway/storage/backends/db/__init__.py b/jiuwenswarm/gateway/storage/backends/db/__init__.py
index 9d469832be..c20f8b3664 100644
--- a/jiuwenswarm/gateway/storage/backends/db/__init__.py
+++ b/jiuwenswarm/gateway/storage/backends/db/__init__.py
@@ -1,17 +1,11 @@
from jiuwenswarm.gateway.storage.backends.db.connection import PersistentDbConnection
from jiuwenswarm.gateway.storage.backends.db.persistent_store import DbPersistentBackend
from jiuwenswarm.gateway.storage.backends.db.reader import (
- is_gateway_db_available,
list_records as list_gateway_db_records,
- resolve_gateway_db_path,
- use_remote_gateway_db,
)
__all__ = [
"DbPersistentBackend",
"PersistentDbConnection",
- "is_gateway_db_available",
"list_gateway_db_records",
- "resolve_gateway_db_path",
- "use_remote_gateway_db",
]
diff --git a/jiuwenswarm/gateway/storage/backends/db/reader.py b/jiuwenswarm/gateway/storage/backends/db/reader.py
index fc37271f35..ff55b54f69 100644
--- a/jiuwenswarm/gateway/storage/backends/db/reader.py
+++ b/jiuwenswarm/gateway/storage/backends/db/reader.py
@@ -1,116 +1,30 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Gateway DB 只读/轻量写(OSS):AgentServer 与 enterprise_config 共用。
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved.
+"""Gateway 本地库 facade(企业版)。
-不依赖 jiuwenclaw-ee。按 ``GATEWAY_*`` 连 sqlite 或 MySQL/PG,与 Gateway 写库同环境变量。
-每网关独立数据库,读写不加行级 ``jiuwenclaw_id`` 隔离。
+经存储屏蔽层入口 ``ensure_db_handler`` 获取 foundation ``DBHandler``,CRUD 调
+``list_records / create / update``。每网关独立数据库,查询不加实例行级隔离。
"""
from __future__ import annotations
-import asyncio
import json
-import os
import re
-from pathlib import Path
+from datetime import datetime, timezone
from 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 logger
+from jiuwenswarm.infrastructure.module_importer import import_manager_config_receiver_module
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
-_DB_PATH: str | None = None
-
-_remote_engine: Any | None = None
-_remote_engine_key: str | None = None
-_remote_engine_lock = asyncio.Lock()
-
PERMISSIONS_CONFIG_TABLE = "permissions_config"
-
-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("[gateway_db_reader] 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("[gateway_db_reader] 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
-
-
-def use_remote_gateway_db() -> bool:
- """企业远程库:``is_enterprise()`` 且 ``GATEWAY_DB_HOST`` 非空。"""
- from jiuwenswarm.common.local_env_config import is_enterprise
-
- if not is_enterprise():
- return False
- return bool(os.getenv("GATEWAY_DB_HOST", "").strip())
-
-
-def is_gateway_db_available() -> bool:
- """远程(有 HOST)或本地 sqlite 文件存在。"""
- if use_remote_gateway_db():
- return True
- return bool(resolve_gateway_db_path())
+# foundation ``list_records`` 默认 limit=100,此处取全部配置行。
+_LIST_LIMIT = 100_000
+# --------------------------------------------------------------------------- #
+# 标识符 / 行转换辅助
+# --------------------------------------------------------------------------- #
def is_safe_ident(name: str) -> bool:
return bool(_SAFE_IDENT.fullmatch(name or ""))
@@ -128,9 +42,8 @@ def _parse_json_string(value: str) -> Any:
def row_to_dict(row: Any) -> dict[str, Any]:
"""DB 行 → dict;字符串 JSON 字段自动 parse。
- 注意:SQLAlchemy ``Row`` 上 ``row.keys`` 会按**列名**解析,不能写成
- ``row.keys()``(会触发 ``NoSuchColumnError: column 'keys'``)。优先用
- ``_mapping``;aiosqlite.Row 等走类型上的 ``keys`` 方法。
+ 兼容 dict / SQLAlchemy ``Row``(``_mapping``)/ foundation ORM 实例
+ (``__table__`` + ``vars``,过滤 ``_sa_`` 内部态)。
"""
if isinstance(row, dict):
items = dict(row)
@@ -142,18 +55,18 @@ def row_to_dict(row: Any) -> dict[str, Any]:
keys_fn = getattr(type(row), "keys", None)
if callable(keys_fn):
items = {k: row[k] for k in keys_fn(row)}
+ elif hasattr(row, "__table__"):
+ items = {k: v for k, v in vars(row).items() if not k.startswith("_sa_")}
else:
items = dict(row)
out: dict[str, Any] = {}
for key, value in items.items():
- if isinstance(value, str):
- out[key] = _parse_json_string(value)
- else:
- out[key] = value
+ out[key] = _parse_json_string(value) if isinstance(value, str) else value
return out
def sort_by_order(rows: list[dict[str, Any]], order_by: str) -> list[dict[str, Any]]:
+ """内存排序兜底,支持 ``-field`` / ``field DESC`` 语法。"""
text = order_by.strip()
if not text:
return rows
@@ -181,346 +94,86 @@ def sort_by_order(rows: list[dict[str, Any]], order_by: str) -> list[dict[str, A
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:
- global _remote_engine, _remote_engine_key
-
- engine = _remote_engine
- _remote_engine = None
- _remote_engine_key = None
- if engine is None:
- return
- try:
- await engine.dispose()
- except Exception as exc: # noqa: BLE001
- logger.warning(
- "[gateway_db_reader] dispose remote gateway db engine 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。"""
- global _remote_engine, _remote_engine_key
-
- db_type = _remote_db_type()
- 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}"
-
- async with _remote_engine_lock:
- if _remote_engine is not None and _remote_engine_key == key:
- return _remote_engine
-
- if _remote_engine is not None:
- logger.info(
- "[gateway_db_reader] remote gateway db config changed (%s -> %s), disposing old engine",
- _remote_engine_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}"
- )
- elif db_type in {"mysql", "mariadb"}:
- url = (
- f"mysql+aiomysql://{user}:{password}"
- f"@{db_host}:{db_port}/{db_name}?charset=utf8mb4"
- )
- else:
- raise RuntimeError(
- f"unsupported GATEWAY_DB_TYPE={db_type!r} for remote gateway db read; "
- "use mysql or postgresql, or unset GATEWAY_DB_HOST for sqlite"
- )
-
- engine = create_async_engine(url, **_gateway_db_pool_kwargs())
- _remote_engine = engine
- _remote_engine_key = key
- logger.info(
- "[gateway_db_reader] 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
+# --------------------------------------------------------------------------- #
+# 存储屏蔽层入口
+# --------------------------------------------------------------------------- #
+async def _handler() -> Any:
+ """经 ``ensure_db_handler`` 获取 foundation ``DBHandler``。"""
+ db_mod = import_manager_config_receiver_module("infrastructure.db")
+ return await db_mod.ensure_db_handler(log_prefix="gateway_db_reader")
- 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
-
-async def list_records_remote(
+# --------------------------------------------------------------------------- #
+# CRUD
+# --------------------------------------------------------------------------- #
+async def list_records(
table: str,
- query: dict[str, Any],
+ query: dict[str, Any] | None = None,
order_by: str = "",
) -> list[dict[str, Any]]:
- from sqlalchemy import text
-
+ """等值 filters 列表查询(每网关独立 DB,不加实例隔离列)。"""
if not is_safe_ident(table or ""):
logger.warning("[gateway_db_reader] invalid table name: %r", table)
return []
- clause, params = build_filter_clause(query, named=True)
- sql = f"SELECT * FROM {table}{clause}"
+ handler = await _handler()
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
- except Exception as exc:
- logger.error(
- "[gateway_db_reader] remote query %s failed (no sqlite fallback): %s",
+ rows = await handler.list_records(
table,
- exc,
+ filters=dict(query or {}),
+ limit=_LIST_LIMIT,
+ offset=0,
+ order_by=(order_by or None),
)
+ return [row_to_dict(r) for r in rows]
+ except Exception as exc: # noqa: BLE001
+ logger.error("[gateway_db_reader] list %s failed: %s", table, exc)
raise
-async def list_records_sqlite(
- table: str,
- query: dict[str, Any],
- order_by: str = "",
-) -> list[dict[str, Any]]:
- if not is_safe_ident(table or ""):
- logger.warning("[gateway_db_reader] invalid table name: %r", table)
- return []
-
- 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("[gateway_db_reader] query %s failed: %s", table, exc)
- return []
-
-
-async def list_records(
- table: str,
- query: dict[str, Any] | None = None,
- order_by: str = "",
-) -> list[dict[str, Any]]:
- """等值 filters 列表查询(调用方已处理好实例隔离)。"""
- if not is_safe_ident(table or ""):
- logger.warning("[gateway_db_reader] invalid table name: %r", table)
- return []
-
- filters = dict(query or {})
- if use_remote_gateway_db():
- return await list_records_remote(table, filters, order_by)
- return await list_records_sqlite(table, filters, order_by)
-
-
async def upsert_permissions_config(
body: dict[str, Any],
*,
source: str = "runtime_persist",
) -> None:
"""单例行 upsert ``permissions_config``(每网关独立 DB,无行级实例隔离)。"""
- 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(body_json, source=source, now=now)
- return
- await _upsert_permissions_sqlite(body_json, source=source, now=now)
-
-
-async def _upsert_permissions_remote(
- body_json: str,
- *,
- 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} ORDER BY id ASC LIMIT 1"),
+ handler = await _handler()
+ rows = await handler.list_records(PERMISSIONS_CONFIG_TABLE, limit=1, offset=0)
+ if rows:
+ existing = row_to_dict(rows[0])
+ row_id = existing.get("id")
+ revision = int(existing.get("revision") or 1) + 1
+ await handler.update(
+ PERMISSIONS_CONFIG_TABLE,
+ {"id": row_id},
+ {
+ "body": body_json,
+ "source": source,
+ "revision": revision,
+ "updated_at": now,
+ },
)
- existing = result.fetchone()
- if existing is not None:
- row_id = int(existing[0])
- 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 id = :id
- """
- ),
- {
- "body": body_json,
- "source": source,
- "revision": revision,
- "updated_at": now,
- "id": row_id,
- },
- )
- else:
- await conn.execute(
- text(
- f"""
- INSERT INTO {table}
- (body, source, revision, created_at, updated_at)
- VALUES (:body, :source, 1, :created_at, :updated_at)
- """
- ),
- {
- "body": body_json,
- "source": source,
- "created_at": now,
- "updated_at": now,
- },
- )
-
-
-async def _upsert_permissions_sqlite(
- body_json: str,
- *,
- source: str,
- now: str,
-) -> None:
- db_path = resolve_gateway_db_path()
- if not db_path:
- raise RuntimeError("gateway db not available")
+ return
+ await handler.create(
+ PERMISSIONS_CONFIG_TABLE,
+ {
+ "body": body_json,
+ "source": source,
+ "revision": 1,
+ "created_at": now,
+ "updated_at": now,
+ },
+ )
- table = PERMISSIONS_CONFIG_TABLE
- async with aiosqlite.connect(db_path) as conn:
- async with conn.execute(
- f"SELECT id, revision FROM {table} ORDER BY id ASC LIMIT 1",
- ) as cursor:
- existing = await cursor.fetchone()
- if existing is not None:
- row_id = int(existing[0])
- revision = int(existing[1] or 1) + 1
- await conn.execute(
- f"""
- UPDATE {table}
- SET body = ?, source = ?, revision = ?, updated_at = ?
- WHERE id = ?
- """,
- (body_json, source, revision, now, row_id),
- )
- else:
- await conn.execute(
- f"""
- INSERT INTO {table}
- (body, source, revision, created_at, updated_at)
- VALUES (?, ?, 1, ?, ?)
- """,
- (body_json, source, now, now),
- )
- await conn.commit()
__all__ = [
"PERMISSIONS_CONFIG_TABLE",
- "build_filter_clause",
- "dispose_remote_engine",
- "get_remote_engine",
- "is_gateway_db_available",
"is_safe_ident",
"list_records",
- "list_records_remote",
- "list_records_sqlite",
- "resolve_gateway_db_path",
"row_to_dict",
"sort_by_order",
"upsert_permissions_config",
- "use_remote_gateway_db",
]
diff --git a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
index 904e1e9473..258b6b0e8f 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
@@ -1,8 +1,7 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Gateway 本地库:企业配置读库 facade(``GATEWAY_*``,不依赖 jiuwenclaw-ee)。
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved.
+"""Gateway 本地库:企业配置读库 facade(企业版)。
-IO 实现见 ``gateway/storage/backends/db/reader``(与 Gateway 写库同环境变量)。
-每网关独立数据库,查询不加实例行级隔离。
+委托 ``gateway/storage/backends/db/reader`` 访问;每网关独立数据库,查询不加实例行级隔离。
"""
from __future__ import annotations
@@ -16,21 +15,13 @@ from .schemas import SLOT_ENTITY_TABLE, TemplateRefSlot
PERMISSIONS_CONFIG_TABLE = _db_reader.PERMISSIONS_CONFIG_TABLE
-resolve_gateway_db_path = _db_reader.resolve_gateway_db_path
-use_remote_gateway_db = _db_reader.use_remote_gateway_db
-is_gateway_db_available = _db_reader.is_gateway_db_available
-
-# 别名:单测可 monkeypatch 本模块上的 ``_list_records_*``
-_list_records_remote = _db_reader.list_records_remote
-_list_records_sqlite = _db_reader.list_records_sqlite
-
async def upsert_permissions_config(
body: dict[str, Any],
*,
source: str = "runtime_persist",
) -> None:
- """单例行 upsert ``permissions_config``(远程或本地 sqlite)。"""
+ """单例行 upsert ``permissions_config``。"""
await _db_reader.upsert_permissions_config(body, source=source)
@@ -61,26 +52,16 @@ async def list_records(
filters: dict[str, Any] | None = None,
order_by: str = "",
) -> list[dict[str, Any]]:
- """列表查询(每网关独立 DB,不加实例隔离列)。
-
- ``is_enterprise()`` + ``GATEWAY_DB_HOST`` 时走远程 MySQL/PG;否则走本地 sqlite。
- """
+ """列表查询(每网关独立 DB,不加实例隔离列)。"""
if not _db_reader.is_safe_ident(table or ""):
logger.warning("[enterprise_config] invalid table name: %r", table)
return []
-
- query = 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 _db_reader.list_records(table, query=filters, order_by=order_by)
__all__ = (
"PERMISSIONS_CONFIG_TABLE",
"fetch_template_by_slot",
- "is_gateway_db_available",
"list_records",
- "resolve_gateway_db_path",
"upsert_permissions_config",
- "use_remote_gateway_db",
)
diff --git a/tests/unit_tests/gateway/test_instance_scope.py b/tests/unit_tests/gateway/test_instance_scope.py
deleted file mode 100644
index 1ae1c2a79c..0000000000
--- a/tests/unit_tests/gateway/test_instance_scope.py
+++ /dev/null
@@ -1,130 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Gateway 企业配置读库相关单测(每网关独立 DB,无实例行级隔离)。"""
-
-from __future__ import annotations
-
-import pytest
-
-
-async def test_gateway_db_list_records_passes_filters(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- monkeypatch.setattr(gateway_db, "use_remote_gateway_db", lambda: False)
-
- async def _sqlite(table, query, order_by):
- assert table == "extension_config_template"
- assert query == {"enabled": True}
- return [{"template_id": "t1"}]
-
- monkeypatch.setattr(gateway_db, "_list_records_sqlite", _sqlite)
- rows = await gateway_db.list_records("extension_config_template", filters={"enabled": True})
- assert rows == [{"template_id": "t1"}]
-
-
-def test_use_remote_gateway_db_requires_enterprise_edition_and_host(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)
- monkeypatch.delenv("GATEWAY_DB_HOST", raising=False)
- assert gateway_db.use_remote_gateway_db() is False
-
- monkeypatch.setenv("GATEWAY_DB_HOST", "127.0.0.1")
- assert gateway_db.use_remote_gateway_db() is False
-
- monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- assert gateway_db.use_remote_gateway_db() is True
-
-
-def test_is_gateway_db_available_remote_without_sqlite(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- monkeypatch.setenv("GATEWAY_DB_HOST", "db.example")
- monkeypatch.setattr(gateway_db, "resolve_gateway_db_path", lambda: None)
- assert gateway_db.is_gateway_db_available() is True
-
-
-async def test_list_records_remote_does_not_fallback_to_sqlite(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- monkeypatch.setenv("GATEWAY_DB_HOST", "db.example")
-
- async def _boom(*_a, **_k):
- raise RuntimeError("remote down")
-
- monkeypatch.setattr(gateway_db, "_list_records_remote", _boom)
-
- sqlite_called = {"ok": False}
-
- async def _sqlite(*_a, **_k):
- sqlite_called["ok"] = True
- return [{"id": 1}]
-
- monkeypatch.setattr(gateway_db, "_list_records_sqlite", _sqlite)
-
- with pytest.raises(RuntimeError, match="remote down"):
- await gateway_db.list_records("model_template", filters={"enabled": True})
- assert sqlite_called["ok"] is False
-
-
-async def test_get_remote_engine_disposes_old_on_config_change(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.gateway.storage.backends.db import reader as db_reader
-
- class _FakeEngine:
- def __init__(self, label: str) -> None:
- self.label = label
- self.disposed = False
-
- async def dispose(self) -> None:
- self.disposed = True
-
- created: list[_FakeEngine] = []
-
- def _fake_create_async_engine(_url: str, **_kwargs: object) -> _FakeEngine:
- engine = _FakeEngine(f"engine-{len(created)}")
- created.append(engine)
- return engine
-
- monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- monkeypatch.setenv("GATEWAY_DB_TYPE", "mysql")
- monkeypatch.setenv("GATEWAY_DB_HOST", "host-a")
- monkeypatch.setenv("GATEWAY_DB_PORT", "3306")
- monkeypatch.setenv("GATEWAY_DB_USER", "root")
- monkeypatch.setenv("GATEWAY_DB_NAME", "gateway")
- monkeypatch.setenv("GATEWAY_DB_PASSWORD", "")
- monkeypatch.setattr(
- "sqlalchemy.ext.asyncio.create_async_engine",
- _fake_create_async_engine,
- )
-
- db_reader._remote_engine = None
- db_reader._remote_engine_key = None
-
- first = await db_reader.get_remote_engine()
- assert first is created[0]
- assert first.disposed is False
-
- monkeypatch.setenv("GATEWAY_DB_HOST", "host-b")
- second = await db_reader.get_remote_engine()
- assert first.disposed is True
- assert second is created[1]
- assert second is not first
- assert second.disposed is False
-
- await db_reader.dispose_remote_engine()
- assert second.disposed is True
- assert db_reader._remote_engine is None
diff --git a/tests/unit_tests/test_app_web_gateway_api_proxy.py b/tests/unit_tests/test_app_web_gateway_api_proxy.py
index c63c699e87..ecb195c4d9 100644
--- a/tests/unit_tests/test_app_web_gateway_api_proxy.py
+++ b/tests/unit_tests/test_app_web_gateway_api_proxy.py
@@ -64,8 +64,6 @@ def test_user_web_runtime_mode_injection_preserves_property_names(
assert "__JIUWENSWARM_EDITION_VALUE__" not in rendered
assert "window.__JIUWEN_LOGIN_AUTH_SIMULATE__ = 'true'" in rendered
assert "__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__" not in rendered
- assert "window.__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__ = 'true'" in rendered
- assert "__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__" not in rendered
def test_login_auth_simulate_config_is_strict_and_defaults_to_true() -> None: