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

fix: delete unuseful info from sandbox

zhaozixuan21e7bab9daff
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.md
index 8c258b46f1..3fb9d37194 100644
--- a/jiuwenbox/README.md
+++ b/jiuwenbox/README.md
@@ -73,34 +73,31 @@ python3 -m build --wheel
uv pip install ./dist/jiuwenbox*.whl
```
+The wheel ships `jiuwenbox/configs/*.yaml` (sources under `src/jiuwenbox/configs/`).
+When `JIUWENBOX_POLICY_PATH` is unset, the server uses the bundled
+`default-policy.yaml`.
+
## Start The Server
### Local Start
-Set the default policy path and start the installed service via the venv
-Python:
+After installing the wheel, start with the bundled default policy:
```bash
-sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
- ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug
+sudo ./.venv/bin/jiuwenbox-server
+# or
+sudo ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug
```
-Use another policy or port by changing the environment variable or uvicorn
-arguments:
+To use a different policy or port, set `JIUWENBOX_POLICY_PATH` to an **absolute**
+path (or, from a dev tree, `src/jiuwenbox/configs/<name>.yaml`):
```bash
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenswarm-policy.yaml" \
+ JIUWENBOX_POLICY_PATH="/absolute/path/to/policy.yaml" \
./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug
```
-The selected policy path is read from:
-
-```bash
-JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml
-```
-
### Docker Start
Build the image:
@@ -136,7 +133,6 @@ Start locally on UDS (same two rules as the ⚠️ in *Local Start*:
```bash
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
./.venv/bin/python -m jiuwenbox.server.launcher
@@ -153,7 +149,7 @@ mkdir -p /tmp/jiuwenbox-sock
sudo env \
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \
- ./run_docker.sh configs/default-policy.yaml
+ ./run_docker.sh src/jiuwenbox/configs/default-policy.yaml
```
`run_docker.sh` skips the management-API TCP port mapping under UDS mode and
@@ -231,13 +227,10 @@ sandbox in boot order.
Local launch:
```bash
-sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
- ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox
+sudo ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox
# Equivalent via env:
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
JIUWENBOX_SAVE_LOGS_DIR=/var/log/jiuwenbox \
./.venv/bin/jiuwenbox-server
```
@@ -521,7 +514,7 @@ When the policy YAML file **only configures `inference_privacy_proxies`** (top-l
The startup log emits `Proxy-only policy detected (no sandbox config); skipping sandbox subsystem startup`, followed by `Inference privacy proxy listening on http://<host>:<port>` so operators can verify the listener address at a glance.
-See the reference config at [`configs/inference-policy.yaml`](configs/inference-policy.yaml).
+See the reference config at [`src/jiuwenbox/configs/inference-policy.yaml`](src/jiuwenbox/configs/inference-policy.yaml) (installed as `jiuwenbox/configs/inference-policy.yaml`).
### Proxy Configuration
diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.md
index c8e79c072b..b2e04a27c9 100644
--- a/jiuwenbox/README_CN.md
+++ b/jiuwenbox/README_CN.md
@@ -69,32 +69,29 @@ python3 -m build --wheel
uv pip install ./dist/jiuwenbox*.whl
```
+构建出的 wheel 已包含 `jiuwenbox/configs/*.yaml`(源码位于 `src/jiuwenbox/configs/`)。
+安装后若不设置 `JIUWENBOX_POLICY_PATH`,服务自动使用包内自带的 `default-policy.yaml`。
+
## 启动服务
### 本地启动
-设置默认 policy 路径,并通过 venv 里的 python 启动已安装的服务:
+安装 wheel 后可直接启动(使用包内默认 policy):
```bash
-sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
- ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug
+sudo ./.venv/bin/jiuwenbox-server
+# 或
+sudo ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug
```
-如需使用其他 policy 或端口,可修改环境变量或 uvicorn 参数:
+如需指定其它 policy 或端口,设置 `JIUWENBOX_POLICY_PATH` 为**绝对路径**(也可在开发树里用 `src/jiuwenbox/configs/<name>.yaml`):
```bash
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenswarm-policy.yaml" \
+ JIUWENBOX_POLICY_PATH="/absolute/path/to/policy.yaml" \
./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug
```
-服务会从以下环境变量读取默认 policy 路径:
-
-```bash
-JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml
-```
-
### Docker 启动
构建镜像:
@@ -129,7 +126,6 @@ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock # 切到 UDS, 路径必
```bash
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
./.venv/bin/python -m jiuwenbox.server.launcher
@@ -146,7 +142,7 @@ mkdir -p /tmp/jiuwenbox-sock
sudo env \
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \
- ./run_docker.sh configs/default-policy.yaml
+ ./run_docker.sh src/jiuwenbox/configs/default-policy.yaml
```
`run_docker.sh` 在 UDS 模式下会自动跳过管理 API 的 TCP 端口映射、把宿主
@@ -218,13 +214,10 @@ ISO 8601 基本格式 (`%Y%m%dT%H%M%S`) 是为了让 `ls` 自然按时间排序
本地启动:
```bash
-sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
- ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox
+sudo ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox
# 或走环境变量, 等价:
sudo env \
- JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \
JIUWENBOX_SAVE_LOGS_DIR=/var/log/jiuwenbox \
./.venv/bin/jiuwenbox-server
```
@@ -501,7 +494,7 @@ sandbox:
启动日志会打印 `Proxy-only policy detected (no sandbox config); skipping sandbox subsystem startup`,随后再输出 `Inference privacy proxy listening on http://<host>:<port>`,便于运维快速确认监听地址。
-参考配置:[`configs/inference-policy.yaml`](configs/inference-policy.yaml)。
+参考配置:[`src/jiuwenbox/configs/inference-policy.yaml`](src/jiuwenbox/configs/inference-policy.yaml)(安装后位于包内 `jiuwenbox/configs/`)。
### 代理配置
diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfile
index 84d98998e7..bf29938182 100644
--- a/jiuwenbox/docker/Dockerfile
+++ b/jiuwenbox/docker/Dockerfile
@@ -27,7 +27,6 @@ WORKDIR /app
COPY pyproject.toml README.md ./
COPY docker/requirements.txt ./docker/requirements.txt
COPY src ./src
-COPY configs ./configs
RUN pip install --break-system-packages --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple build setuptools wheel \
&& pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple -r ./docker/requirements.txt \
diff --git a/jiuwenbox/pyproject.toml b/jiuwenbox/pyproject.toml
index 36663bc25a..a756056801 100644
--- a/jiuwenbox/pyproject.toml
+++ b/jiuwenbox/pyproject.toml
@@ -34,6 +34,9 @@ jiuwenbox-server = "jiuwenbox.server.launcher:main"
where = ["src"]
include = ["jiuwenbox*"]
+[tool.setuptools.package-data]
+jiuwenbox = ["configs/*.yaml"]
+
[tool.pytest.ini_options]
testpaths = ["tests"]
markers = [
diff --git a/jiuwenbox/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.sh
index 6bab2ea560..7cb1e57cf8 100755
--- a/jiuwenbox/scripts/run_docker.sh
+++ b/jiuwenbox/scripts/run_docker.sh
@@ -37,7 +37,7 @@ SAVE_LOGS_CONTAINER_DIR="${JIUWENBOX_SAVE_LOGS_CONTAINER_DIR:-/var/log/jiuwenbox
POLICY_CONFIG=""
CONTAINER_POLICY_PATH="/app/runtime-config/policy.yaml"
-CONTAINER_DEFAULT_POLICY_PATH="/app/configs/default-policy.yaml"
+# Unset JIUWENBOX_POLICY_PATH → launcher uses bundled ``jiuwenbox/configs/default-policy.yaml``.
DOCKER_ENV_ARGS=()
DOCKER_VOLUME_ARGS=()
DOCKER_PORT_ARGS=()
@@ -59,20 +59,20 @@ Options:
Examples (HTTP, default):
scripts/run_docker.sh
- scripts/run_docker.sh configs/default-policy.yaml
+ scripts/run_docker.sh src/jiuwenbox/configs/default-policy.yaml
JIUWENBOX_HOST_PORT=18321 scripts/run_docker.sh
Examples (Unix Domain Socket):
mkdir -p /tmp/jiuwenbox-sock
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \
- scripts/run_docker.sh configs/default-policy.yaml
+ scripts/run_docker.sh src/jiuwenbox/configs/default-policy.yaml
curl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health
Examples (persist sandbox audit log to host):
scripts/run_docker.sh --save-logs /tmp/jiuwenbox-logs
- scripts/run_docker.sh configs/default-policy.yaml --save-logs /tmp/jiuwenbox-logs
+ scripts/run_docker.sh src/jiuwenbox/configs/default-policy.yaml --save-logs /tmp/jiuwenbox-logs
# ls /tmp/jiuwenbox-logs
# <id>-20260515T112345.audit.log
EOF
@@ -81,7 +81,7 @@ EOF
# 第一遍扫描: 把脚本自己识别的 long flag (目前只有 --save-logs) 从 ``$@``
# 里抠出来, 剩下的位置参数 + 透传给 ``docker run`` 的尾部都保留原顺序。
# 这样用户既可以写 ``run_docker.sh --save-logs DIR configs/foo.yaml``
-# 也可以写 ``run_docker.sh configs/foo.yaml --save-logs DIR``, 而原来"第一个
+# 也可以写 ``run_docker.sh path/to/foo.yaml --save-logs DIR``, 而原来"第一个
# 非 -* 实参当 policy-config" / "尾部任意 docker run 参数透传" 的行为不变。
SAVE_LOGS_CLI=""
REMAINING_ARGS=()
@@ -218,8 +218,7 @@ if [[ -n "$POLICY_CONFIG" ]]; then
DOCKER_VOLUME_ARGS+=(-v "${POLICY_CONFIG_ABS}:${CONTAINER_POLICY_PATH}:ro")
echo " policy: $POLICY_CONFIG_ABS"
else
- DOCKER_ENV_ARGS+=(-e "JIUWENBOX_POLICY_PATH=${CONTAINER_DEFAULT_POLICY_PATH}")
- echo " policy: ${CONTAINER_DEFAULT_POLICY_PATH} (container default)"
+ echo " policy: bundled default-policy.yaml (wheel)"
fi
echo
diff --git a/jiuwenbox/src/jiuwenbox/bundled_configs.py b/jiuwenbox/src/jiuwenbox/bundled_configs.py
new file mode 100644
index 0000000000..527d69abbd
--- /dev/null
+++ b/jiuwenbox/src/jiuwenbox/bundled_configs.py
@@ -0,0 +1,20 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+"""Bundled policy YAML files shipped inside the jiuwenbox package."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import jiuwenbox
+
+_CONFIGS_DIR = Path(jiuwenbox.__file__).resolve().parent / "configs"
+
+
+def configs_dir() -> Path:
+ """Directory containing default policy templates bundled with the wheel."""
+ return _CONFIGS_DIR
+
+
+def default_policy_path() -> Path:
+ """Default ``default-policy.yaml`` path when ``JIUWENBOX_POLICY_PATH`` is unset."""
+ return _CONFIGS_DIR / "default-policy.yaml"
diff --git a/jiuwenbox/configs/code-agent-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/code-agent-policy.yaml
similarity index 100%
rename from jiuwenbox/configs/code-agent-policy.yaml
rename to jiuwenbox/src/jiuwenbox/configs/code-agent-policy.yaml
diff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/default-policy.yaml
similarity index 100%
rename from jiuwenbox/configs/default-policy.yaml
rename to jiuwenbox/src/jiuwenbox/configs/default-policy.yaml
diff --git a/jiuwenbox/configs/enterprise-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml
similarity index 100%
rename from jiuwenbox/configs/enterprise-policy.yaml
rename to jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml
diff --git a/jiuwenbox/configs/inference-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/inference-policy.yaml
similarity index 100%
rename from jiuwenbox/configs/inference-policy.yaml
rename to jiuwenbox/src/jiuwenbox/configs/inference-policy.yaml
diff --git a/jiuwenbox/src/jiuwenbox/logging_config.py b/jiuwenbox/src/jiuwenbox/logging_config.py
index a9ed69562a..8dc569ec79 100644
--- a/jiuwenbox/src/jiuwenbox/logging_config.py
+++ b/jiuwenbox/src/jiuwenbox/logging_config.py
@@ -19,6 +19,20 @@ def _set_handler_formatters(logger: logging.Logger, formatter: logging.Formatter
handler.setFormatter(formatter)
+def patch_uvicorn_logging() -> None:
+ """Patch uvicorn's default LOGGING_CONFIG and rename ``uvicorn.error`` logger.
+
+ Uvicorn uses the logger name ``uvicorn.error`` for normal server lifecycle
+ messages (not errors). Rename it to ``uvicorn`` for clearer log output, and
+ apply jiuwenbox's timestamped format to the default formatter.
+ """
+ from uvicorn.config import LOGGING_CONFIG
+
+ LOGGING_CONFIG["formatters"]["default"]["fmt"] = LOG_FORMAT
+ LOGGING_CONFIG["formatters"]["default"]["datefmt"] = LOG_DATE_FORMAT
+ logging.getLogger("uvicorn.error").name = "uvicorn"
+
+
def configure_logging(level: int = logging.INFO) -> None:
"""Configure process logging with jiuwenbox's default timestamped format."""
logging.basicConfig(level=level, format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
@@ -26,3 +40,4 @@ def configure_logging(level: int = logging.INFO) -> None:
_set_handler_formatters(logging.getLogger(), formatter)
for logger_name in UVICORN_LOGGER_NAMES:
_set_handler_formatters(logging.getLogger(logger_name), formatter)
+ patch_uvicorn_logging()
\ No newline at end of file
diff --git a/jiuwenbox/src/jiuwenbox/server/launcher.py b/jiuwenbox/src/jiuwenbox/server/launcher.py
index 8829839cf6..c497b511e3 100644
--- a/jiuwenbox/src/jiuwenbox/server/launcher.py
+++ b/jiuwenbox/src/jiuwenbox/server/launcher.py
@@ -25,6 +25,8 @@ from pathlib import Path
from typing import Tuple, Union
from urllib.parse import urlparse
+from jiuwenbox.logging_config import configure_logging, patch_uvicorn_logging
+
logger = logging.getLogger("jiuwenbox.server.launcher")
ENV_LISTEN = "JIUWENBOX_LISTEN"
@@ -221,6 +223,9 @@ def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
args = parser.parse_args(argv)
+ log_level = getattr(logging, args.log_level.upper(), logging.INFO)
+ configure_logging(level=log_level)
+
# 启动期错误报告 (URI 解析 / uvicorn 导入 / UDS 文件冲突) 走 logger.error,
# 而非 print(..., file=sys.stderr)。Python 的 ``logging.lastResort`` 在无
# 自定义 handler 时会把 ERROR 级别消息写入 stderr, 与原 print 行为对齐;
@@ -252,6 +257,8 @@ def main(argv: list[str] | None = None) -> int:
logger.error("jiuwenbox-server: uvicorn is required (%s)", exc)
return 3
+ patch_uvicorn_logging()
+
uvicorn_kwargs: dict = {"log_level": args.log_level}
if spec[0] == "http":
_, host, port = spec
diff --git a/jiuwenbox/src/jiuwenbox/server/policy_reader.py b/jiuwenbox/src/jiuwenbox/server/policy_reader.py
index cf604f0771..a60d00baa7 100644
--- a/jiuwenbox/src/jiuwenbox/server/policy_reader.py
+++ b/jiuwenbox/src/jiuwenbox/server/policy_reader.py
@@ -12,6 +12,7 @@ from pathlib import Path
import yaml
+from jiuwenbox.bundled_configs import default_policy_path
from jiuwenbox.logging_config import configure_logging
from jiuwenbox.models.policy import SecurityPolicy
from jiuwenbox.server.policy_engine import PolicyEngine
@@ -38,18 +39,42 @@ class PolicyReader:
policy_path: Path | None = None,
) -> None:
self.policy_engine = policy_engine or PolicyEngine()
- self.policy_path = (
- Path(policy_path)
- if policy_path is not None
- else self._resolve_policy_path()
- )
+ if policy_path is not None:
+ self.policy_path = Path(policy_path)
+ self._policy_source = "constructor"
+ else:
+ self.policy_path = self._resolve_policy_path()
+ if os.environ.get(JIUWENBOX_POLICY_PATH_ENV):
+ self._policy_source = JIUWENBOX_POLICY_PATH_ENV
+ else:
+ self._policy_source = "bundled default"
+ self._log_resolved_policy_path()
+
+ def _log_resolved_policy_path(self) -> None:
+ try:
+ resolved = self.policy_path.resolve()
+ except OSError:
+ resolved = self.policy_path
+ if resolved.exists():
+ logger.info(
+ "Loading security policy from %s (%s)",
+ resolved,
+ self._policy_source,
+ )
+ else:
+ logger.warning(
+ "Security policy file not found at %s (%s); "
+ "will fall back to SecurityPolicy defaults on load",
+ resolved,
+ self._policy_source,
+ )
@staticmethod
def _resolve_policy_path() -> Path:
env_path = os.environ.get(JIUWENBOX_POLICY_PATH_ENV)
if env_path:
return Path(env_path).expanduser()
- return Path(__file__).resolve().parents[3] / "configs" / "default-policy.yaml"
+ return default_policy_path()
def load_policy(self) -> SecurityPolicy:
if self.policy_path.exists():
diff --git a/jiuwenbox/tests/integration/test_inference_privacy_proxy.py b/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
index 73e6311ac4..ee917e92a8 100644
--- a/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
+++ b/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
@@ -7,6 +7,7 @@ import logging
import os
import socket
import threading
+import time
import httpx
import pytest
@@ -35,7 +36,7 @@ def manager():
@pytest.fixture
-def proxy_route_factory(http_target_port, mock_server_host_for_docker):
+def proxy_route_factory(http_target_port, proxy_target_host):
"""Factory to create ProxyRoute objects with custom parameters.
Args:
@@ -48,17 +49,147 @@ def proxy_route_factory(http_target_port, mock_server_host_for_docker):
def create_route(path_prefix: str, api_key: str = "sk-test-key"):
return ProxyRoute(
path_prefix=path_prefix,
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_target_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_target_port}",
api_key=api_key,
)
return create_route
[email protected](scope="session")
+def proxy_port_session(pytestconfig) -> int:
+ return (
+ pytestconfig.getoption("proxy_port")
+ or int(os.environ.get("JIUWENBOX_PROXY_PORT", "8322"))
+ )
+
+
[email protected](scope="session")
+def proxy_target_host(
+ server_url_session,
+ proxy_host_from_test,
+ proxy_port_session,
+ simple_http_target,
+):
+ """Detect target host reachable by proxy without creating sandboxes.
+
+ In proxy-only mode, `/api/v1/sandboxes` is intentionally unavailable.
+ We therefore probe candidate host IPs by creating a temporary proxy route
+ and checking real forwarding through the proxy listener.
+ """
+ if server_url_session.startswith("unix://"):
+ pytest.skip(
+ "proxy integration tests require a TCP API endpoint; "
+ f"got {server_url_session!r}",
+ )
+
+ candidates = ("127.0.0.1", "172.17.0.1")
+ probe_errors: list[str] = []
+
+ with httpx.Client(base_url=server_url_session, timeout=10.0) as api_client:
+ for candidate in candidates:
+ route_name = f"_probe_{candidate.replace('.', '_')}_{int(time.time() * 1000)}"
+ path_prefix = f"/{route_name}"
+ target_endpoint = f"http://{candidate}:{simple_http_target}"
+ try:
+ create_response = api_client.post(
+ "/api/v1/proxies",
+ json={
+ "path_prefix": path_prefix,
+ "target_endpoint": target_endpoint,
+ },
+ )
+ if create_response.status_code != 201:
+ probe_errors.append(
+ f"{candidate}: create route failed ({create_response.status_code})"
+ )
+ continue
+
+ start_response = api_client.post(f"/api/v1/proxies/{route_name}/start")
+ if start_response.status_code != 200:
+ probe_errors.append(
+ f"{candidate}: start route failed ({start_response.status_code})"
+ )
+ continue
+
+ forward_result = _proxy_http_get(
+ proxy_host_from_test,
+ proxy_port_session,
+ f"{path_prefix}/test",
+ timeout=3.0,
+ )
+ if "200 OK" in forward_result:
+ return candidate
+ probe_errors.append(
+ f"{candidate}: forward probe failed ({forward_result.splitlines()[0]})"
+ )
+ except Exception as exc:
+ probe_errors.append(f"{candidate}: exception ({exc})")
+ finally:
+ api_client.post(f"/api/v1/proxies/{route_name}/stop")
+ api_client.delete(f"/api/v1/proxies/{route_name}")
+
+ raise RuntimeError(
+ "Failed to detect proxy target host without sandbox. "
+ f"Tried {candidates}. Details: {'; '.join(probe_errors)}"
+ )
+
+
@pytest.fixture
-def integration_target_endpoint(simple_http_target, docker_gateway_ip):
- """Target endpoint for integration tests (API server perspective)."""
- gateway_ip = docker_gateway_ip["gateway_ip"]
- return f"http://{gateway_ip}:{simple_http_target}"
+def integration_target_endpoint(simple_http_target, proxy_target_host):
+ """Target endpoint for integration tests (proxy runtime perspective)."""
+ return f"http://{proxy_target_host}:{simple_http_target}"
+
+
+def _wait_tcp_ready(host: str, port: int, timeout_seconds: float = 10.0) -> bool:
+ deadline = time.monotonic() + timeout_seconds
+ while time.monotonic() < deadline:
+ try:
+ with socket.create_connection((host, port), timeout=1.0):
+ return True
+ except OSError:
+ time.sleep(0.1)
+ return False
+
+
[email protected](scope="session")
+def llm_available(test_llm_endpoint, test_llm_api_key):
+ """Best-effort LLM availability probe without sandbox dependency."""
+ if not test_llm_endpoint or not test_llm_api_key:
+ return False
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ response = client.get(
+ f"{test_llm_endpoint.rstrip('/')}/models",
+ headers={"Authorization": f"Bearer {test_llm_api_key}"},
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
[email protected](scope="session")
+def mock_llm_server_ready(mock_llm_server, proxy_target_host):
+ """Ensure mock LLM server is reachable from proxy-side host mapping."""
+ http_port = mock_llm_server["http_port"]
+ process = mock_llm_server["process"]
+ if _wait_tcp_ready(proxy_target_host, http_port, timeout_seconds=10.0):
+ return mock_llm_server
+
+ stderr_detail = ""
+ if process.poll() is not None and process.stderr is not None:
+ try:
+ stderr_raw = process.stderr.read()
+ stderr_text = stderr_raw.decode(errors="replace") if stderr_raw else ""
+ if stderr_text.strip():
+ stderr_detail = f" process exited with stderr: {stderr_text.strip()}"
+ except Exception:
+ logger.debug("process.poll() failed")
+
+ raise RuntimeError(
+ f"mock_llm_server not reachable at {proxy_target_host}:{http_port}; "
+ f"this usually means the fixture subprocess failed to start or host<->container "
+ f"port path is blocked.{stderr_detail}"
+ )
def _proxy_http_get(proxy_host: str, proxy_port: int, path: str, timeout: float = 5.0) -> str:
@@ -256,7 +387,7 @@ class TestProxyManagerCRUD:
proxy_route_factory,
proxy_listen_port,
http_target_port,
- mock_server_host_for_docker,
+ proxy_target_host,
):
route = proxy_route_factory("/test")
config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])
@@ -264,7 +395,7 @@ class TestProxyManagerCRUD:
new_route = ProxyRoute(
path_prefix="/test",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_target_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_target_port}",
api_key="sk-new-key",
)
new_config = InferencePrivacyProxyConfig(routes=[new_route])
@@ -273,7 +404,7 @@ class TestProxyManagerCRUD:
assert result["name"] == "test"
proxy = await manager.get_proxy("test")
- assert proxy["route"]["target_endpoint"] == f"http://{mock_server_host_for_docker}:{http_target_port}"
+ assert proxy["route"]["target_endpoint"] == f"http://{proxy_target_host}:{http_target_port}"
class TestProxyManagerLifecycle:
@@ -555,7 +686,7 @@ class TestInferencePrivacyProxyHTTPRouting:
"""Tests for actual HTTP request routing."""
@pytest.mark.asyncio
- async def test_http_request_routing(self, proxy_listen_port, mock_server_host_for_docker):
+ async def test_http_request_routing(self, proxy_listen_port, proxy_target_host):
"""Test HTTP request routing with mock target server."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0", 0))
@@ -577,7 +708,7 @@ class TestInferencePrivacyProxyHTTPRouting:
routes=[
ProxyRoute(
path_prefix="/test",
- target_endpoint=f"http://{mock_server_host_for_docker}:{target_port}",
+ target_endpoint=f"http://{proxy_target_host}:{target_port}",
api_key="sk-test-key",
),
],
@@ -681,16 +812,16 @@ class TestInferencePrivacyProxyWithMockServer:
"""Tests using the mock_llm_server fixture."""
@pytest.mark.asyncio
- async def test_http_proxy_with_mock_server(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):
+ async def test_http_proxy_with_mock_server(self, mock_llm_server_ready, proxy_listen_port, proxy_target_host):
"""Test HTTP proxy forwarding to mock LLM server."""
- http_port = mock_llm_server["http_port"]
+ http_port = mock_llm_server_ready["http_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/mock",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="sk-sandbox-key",
),
],
@@ -726,16 +857,16 @@ class TestInferencePrivacyProxyWithMockServer:
await proxy.stop()
@pytest.mark.asyncio
- async def test_https_proxy_with_mock_server(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):
+ async def test_https_proxy_with_mock_server(self, mock_llm_server_ready, proxy_listen_port, proxy_target_host):
"""Test HTTPS proxy forwarding to mock LLM server."""
- https_port = mock_llm_server["https_port"]
+ https_port = mock_llm_server_ready["https_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/mock",
- target_endpoint=f"https://{mock_server_host_for_docker}:{https_port}",
+ target_endpoint=f"https://{proxy_target_host}:{https_port}",
api_key="sk-sandbox-key",
skip_cert_verify=True,
),
@@ -772,16 +903,16 @@ class TestInferencePrivacyProxyWithMockServer:
await proxy.stop()
@pytest.mark.asyncio
- async def test_anthropic_api_key_injection(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):
+ async def test_anthropic_api_key_injection(self, mock_llm_server_ready, proxy_listen_port, proxy_target_host):
"""Test Anthropic-style X-Api-Key header injection."""
- http_port = mock_llm_server["http_port"]
+ http_port = mock_llm_server_ready["http_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/anthropic",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="sk-ant-api03-test-key",
),
],
@@ -1934,22 +2065,22 @@ class TestRouteLongestPrefixMatching:
@pytest.mark.asyncio
async def test_longer_prefix_wins_over_string_prefix_collision(
- self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker
+ self, mock_llm_server_ready, proxy_listen_port, proxy_target_host
):
"""Test '/api-v2' wins over '/api' for request '/api-v2/chat'."""
- http_port = mock_llm_server["http_port"]
+ http_port = mock_llm_server_ready["http_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/api",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="generic-key",
),
ProxyRoute(
path_prefix="/api-v2",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="specific-key",
),
],
@@ -1986,22 +2117,22 @@ class TestRouteLongestPrefixMatching:
@pytest.mark.asyncio
async def test_shorter_prefix_matches_when_no_longer_match(
- self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker
+ self, mock_llm_server_ready, proxy_listen_port, proxy_target_host
):
"""Test '/api' matches '/api/chat' when '/api-v2' doesn't match."""
- http_port = mock_llm_server["http_port"]
+ http_port = mock_llm_server_ready["http_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/api",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="generic-key",
),
ProxyRoute(
path_prefix="/api-v2",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="specific-key",
),
],
@@ -2038,22 +2169,22 @@ class TestRouteLongestPrefixMatching:
@pytest.mark.asyncio
async def test_route_order_does_not_affect_matching(
- self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker
+ self, mock_llm_server_ready, proxy_listen_port, proxy_target_host
):
"""Route order should not affect longest-prefix matching."""
- http_port = mock_llm_server["http_port"]
+ http_port = mock_llm_server_ready["http_port"]
config = InferencePrivacyProxyConfig(
listen_port=proxy_listen_port,
routes=[
ProxyRoute(
path_prefix="/api-v2",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="specific-key",
),
ProxyRoute(
path_prefix="/api",
- target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",
+ target_endpoint=f"http://{proxy_target_host}:{http_port}",
api_key="generic-key",
),
],
diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.py
index 488de0a515..e0610669c6 100644
--- a/jiuwenbox/tests/integration/test_server_api_default.py
+++ b/jiuwenbox/tests/integration/test_server_api_default.py
@@ -14,12 +14,13 @@ import httpx
import pytest
import yaml
+from jiuwenbox.bundled_configs import default_policy_path
from jiuwenbox.models.policy import SecurityPolicy
from jiuwenbox.supervisor import network as network_module
from jiuwenbox.supervisor.bwrap import BwrapConfig
_DEFAULT_POLICY = yaml.safe_load(
- (Path(__file__).resolve().parents[2] / "configs" / "default-policy.yaml").read_text(encoding="utf-8")
+ default_policy_path().read_text(encoding="utf-8")
)
_DEFAULT_FILESYSTEM_POLICY = _DEFAULT_POLICY["filesystem_policy"]
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
index f7efe58ccf..a485bf6883 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
@@ -23,7 +23,6 @@ type SandboxResponse = {
effective_files?: SandboxEffectiveFiles;
jiuwenbox?: { host?: string; port?: number; ready?: boolean };
agent_recreated?: boolean;
- rebuilt_modes?: string[];
jiuwenbox_stopped?: boolean;
};
@@ -109,7 +108,6 @@ export function createSandboxCommand(): SlashCommand {
usage: "/sandbox <enable|disable|exclude|files> ...",
example: "/sandbox enable",
kind: CommandKind.BUILT_IN,
- hidden: true,
takesArgs: true,
action: async (ctx, args) => {
const raw = (args ?? "").trim();
@@ -133,12 +131,11 @@ export function createSandboxCommand(): SlashCommand {
const jb = payload.jiuwenbox;
const host = jb?.host ?? "127.0.0.1";
const port = jb?.port ?? 8321;
- const rebuilt = payload.rebuilt_modes ?? [];
- const rebuiltText = rebuilt.length ? ` (rebuilt: ${rebuilt.join(", ")})` : "";
+ const jbText = `jiuwenbox @ ${host}:${port}`;
ctx.addItem(
addInfo(
ctx.sessionId,
- `Sandbox enabled (jiuwenbox @ ${host}:${port}); agent rebuilt${rebuiltText}.`,
+ `Sandbox enabled (${jbText}).`,
"s",
),
);
@@ -148,21 +145,19 @@ export function createSandboxCommand(): SlashCommand {
if (sub === "disable") {
const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "disable" });
- const rebuilt = payload.rebuilt_modes ?? [];
- const rebuiltText = rebuilt.length ? ` (rebuilt: ${rebuilt.join(", ")})` : "";
const jb = payload.jiuwenbox;
let jbText = "";
if (payload.jiuwenbox_stopped) {
const host = jb?.host ?? "127.0.0.1";
const port = jb?.port ?? 8321;
- jbText = `; jiuwenbox stopped @ ${host}:${port}`;
+ jbText = `jiuwenbox stopped @ ${host}:${port}`;
} else if (jb?.host && jb?.port) {
- jbText = `; jiuwenbox @ ${jb.host}:${jb.port} left running (external)`;
+ jbText = `jiuwenbox @ ${jb.host}:${jb.port} left running (external)`;
}
ctx.addItem(
addInfo(
ctx.sessionId,
- `Sandbox disabled; agent rebuilt${rebuiltText}${jbText}.`,
+ `Sandbox disabled (${jbText}).`,
"s",
),
);
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index fc4bbb0fc6..3860663e26 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -1640,15 +1640,18 @@ def _looks_like_bare_filename(value: str) -> bool:
def _jiuwenbox_configs_dir() -> Path | None:
"""探测仓库或安装位置上的 ``jiuwenbox/configs/`` 目录。
- 优先在仓库目录树里寻找 (开发场景, ``code_agent/jiuwenbox/configs``);
- 失败再尝试已 ``pip install`` 的 jiuwenbox 包同级 ``configs/``。
+ 优先在仓库目录树里寻找 (开发场景, ``jiuwenbox/src/jiuwenbox/configs``);
+ 失败再尝试已 ``pip install`` 的 jiuwenbox 包内 ``configs/``。
"""
here = Path(__file__).resolve()
for ancestor in here.parents[1:7]:
- candidate = ancestor / "jiuwenbox" / "configs"
- if candidate.is_dir():
- return candidate
+ for candidate in (
+ ancestor / "jiuwenbox" / "src" / "jiuwenbox" / "configs",
+ ancestor / "jiuwenbox" / "configs",
+ ):
+ if candidate.is_dir():
+ return candidate
try:
import jiuwenbox # type: ignore[import-not-found]
except ImportError:
@@ -1657,9 +1660,7 @@ def _jiuwenbox_configs_dir() -> Path | None:
pkg_dir = Path(jiuwenbox.__file__).resolve().parent
except Exception: # noqa: BLE001
return None
- # wheel 安装版: ``scripts/build.sh`` 把 ``jiuwenbox/configs/`` 临时 stage 到
- # ``jiuwenbox/src/jiuwenbox/configs/`` 后再打包, 安装后表现为
- # ``<site-packages>/jiuwenbox/configs/``。优先按这个布局找。
+ # wheel 安装版: policy 模板随包打入 ``<site-packages>/jiuwenbox/configs/``。
direct = pkg_dir / "configs"
if direct.is_dir():
return direct
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 04c440d23a..f1557c169a 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -3076,7 +3076,7 @@ class AgentWebSocketServer:
logger.warning("[command.sandbox] persist sandbox endpoint failed: %s", exc)
runtime = update_sandbox_runtime({"enabled": True})
- rebuilt_modes = await self._agent_manager.recreate_agent(channel_id, immediate=True)
+ await self._agent_manager.recreate_agent(channel_id, immediate=True)
return {
"runtime": runtime,
@@ -3094,17 +3094,12 @@ class AgentWebSocketServer:
"startup_mode": startup_mode,
"policy_path": str(policy_path),
},
- "agent_recreated": True,
- "rebuilt_modes": rebuilt_modes,
+ "agent_recreated": True
}
async def _handle_sandbox_disable(self, channel_id: str) -> dict[str, Any]:
runtime = update_sandbox_runtime({"enabled": False})
- # 先重建 agent: 新 agent 在 enabled=False 下不再装载 jiuwenbox provider,
- # 不会有新请求打到将要关闭的子进程; 老 agent 上的 in-flight 调用也由
- # recreate_agent 内部完成切换。然后再关 jiuwenbox 子进程, 避免出现
- # "老 agent 还活着 + jiuwenbox 已死" 的中间窗口导致 tool call 报连接错误。
- rebuilt_modes = await self._agent_manager.recreate_agent(channel_id, immediate=True)
+ await self._agent_manager.recreate_agent(channel_id, immediate=True)
# 记录关闭前的端点用于回执 (external 模式下 runner 没拥有进程, 会是 None)。
owned_endpoint = self._jiuwenbox_runner.get_owned_endpoint()
@@ -3127,7 +3122,6 @@ class AgentWebSocketServer:
payload: dict[str, Any] = {
"runtime": runtime,
"agent_recreated": True,
- "rebuilt_modes": rebuilt_modes,
"jiuwenbox_stopped": jiuwenbox_stopped,
}
if owned_endpoint is not None:
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index c2e2deafce..60a7ba56ac 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -339,7 +339,7 @@ class AgentManager:
)
logger.info(f"channel {channel_id} reload agent config success.")
- async def recreate_agent(self, channel_id: str, *, immediate: bool = True) -> list[str]:
+ async def recreate_agent(self, channel_id: str, *, immediate: bool = True) -> None:
"""重建指定 channel 的所有 agent 实例.
用于 ``/sandbox enable/disable`` 等需要重新构建 ``SysOperationCard`` 的场景.
@@ -353,9 +353,6 @@ class AgentManager:
Args:
channel_id: 通道 ID.
immediate: 是否立即重建 (默认 True).
-
- Returns:
- 被重建的 mode 列表.
"""
channel_key = channel_id or "default"
agents = self.agents.get(channel_key)
@@ -364,7 +361,6 @@ class AgentManager:
"[AgentManager] recreate_agent: no active agent on channel %s",
channel_key,
)
- return []
# 1. 备份 (mode -> create_params)
existing_modes = list(agents.keys())
@@ -401,7 +397,6 @@ class AgentManager:
"[AgentManager] recreate_agent: channel %s will rebuild on next get_agent()",
channel_key,
)
- return existing_modes
# 3. 立即按原参数重建
for mode_key, params in backup_params.items():
@@ -424,7 +419,6 @@ class AgentManager:
channel_key,
existing_modes,
)
- return existing_modes
async def process_message(self, request: Any) -> Any:
"""处理非流式请求.
diff --git a/scripts/build.sh b/scripts/build.sh
index ac3b9f3047..81b3a5f196 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -41,35 +41,12 @@ if [[ -d "$NODE_MODULES" ]]; then
NODE_MODULES_MOVED=true
fi
-# 把 jiuwenbox/configs 临时 stage 到 jiuwenbox/src/jiuwenbox/configs,使其
-# 落在 ``jiuwenbox`` 包目录内, 这样 [tool.setuptools.package-data] 才能把它
-# 随 wheel 一并打入 (setuptools 不支持把包外目录作为 package_data 引入)。
-JBX_CFG_SRC="$PROJECT_ROOT/jiuwenbox/configs"
-JBX_CFG_DST="$PROJECT_ROOT/jiuwenbox/src/jiuwenbox/configs"
-JBX_CFG_STAGED=false
-if [[ -d "$JBX_CFG_SRC" ]]; then
- if [[ -e "$JBX_CFG_DST" ]]; then
- echo "[build] 警告: $JBX_CFG_DST 已存在, 跳过 stage (可能是上一次未清理)" >&2
- else
- echo "[build] 临时 stage jiuwenbox configs → $JBX_CFG_DST"
- cp -R "$JBX_CFG_SRC" "$JBX_CFG_DST"
- JBX_CFG_STAGED=true
- fi
-else
- echo "[build] 警告: 未找到 $JBX_CFG_SRC, wheel 中不会带 jiuwenbox/configs" >&2
-fi
-
cleanup() {
# 恢复 node_modules
if [[ "$NODE_MODULES_MOVED" == "true" && -d "$NODE_MODULES_BAK" ]]; then
mv "$NODE_MODULES_BAK" "$NODE_MODULES"
echo "[build] 已恢复 node_modules"
fi
- # 清理 jiuwenbox configs 的 staging 副本
- if [[ "$JBX_CFG_STAGED" == "true" && -d "$JBX_CFG_DST" ]]; then
- rm -rf "$JBX_CFG_DST"
- echo "[build] 已清理 staged jiuwenbox configs"
- fi
}
trap cleanup EXIT