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

feat(jiuwenclaw): support single-machine multi-instance operation

openJiuwen-botcccd1763a821
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
index 5faa9dc094..157735023d 100644
--- a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
@@ -15,6 +15,8 @@ from openjiuwen.harness.prompts import PromptSection
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenclaw.utils import get_config_dir
+from jiuwenclaw.utils import get_agent_workspace_dir
+
_CN_WEEKDAYS = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
@@ -139,7 +141,7 @@ class RuntimePromptRail(DeepAgentRail):
if self._channel == "tui":
# Trusted directories policy for TUI mode
if self._trusted_dirs and len(self._trusted_dirs) > 0:
- workspace_dir = "~/.jiuwenclaw/agent/jiuwenclaw_workspace"
+ workspace_dir = str(get_agent_workspace_dir())
dirs_display = ", ".join(self._trusted_dirs)
if self._language == "cn":
trusted_dirs_content = (
diff --git a/jiuwenclaw/agentserver/extensions/rail_manager.py b/jiuwenclaw/agentserver/extensions/rail_manager.py
index b53cea833a..6f238eb508 100644
--- a/jiuwenclaw/agentserver/extensions/rail_manager.py
+++ b/jiuwenclaw/agentserver/extensions/rail_manager.py
@@ -14,6 +14,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, List
+from jiuwenclaw.utils import get_agent_workspace_dir
+
logger = logging.getLogger(__name__)
@@ -65,8 +67,7 @@ class RailManager:
if hasattr(self, "_initialized"):
return
- home_dir = Path.home()
- self._extensions_dir = home_dir / ".jiuwenclaw" / "agent" / "jiuwenclaw_workspace" / "extensions"
+ self._extensions_dir = get_agent_workspace_dir() / "extensions"
self._config_file = self._extensions_dir / "extensions_config.json"
# 确保目录存在
diff --git a/jiuwenclaw/agentserver/permissions/tiered_policy.py b/jiuwenclaw/agentserver/permissions/tiered_policy.py
index 474e696093..6ca2dbc8af 100644
--- a/jiuwenclaw/agentserver/permissions/tiered_policy.py
+++ b/jiuwenclaw/agentserver/permissions/tiered_policy.py
@@ -20,6 +20,7 @@ from jiuwenclaw.agentserver.permissions.shell_ast import (
ShellAstParseResult,
parse_shell_for_permission,
)
+from jiuwenclaw.utils import get_config_dir
logger = logging.getLogger(__name__)
@@ -82,7 +83,7 @@ def _resolve_builtin_rules_yaml_path() -> Path | None:
user_path = Path(user_dir) / "builtin_rules.yaml"
if user_path.is_file():
return user_path
- fallback_user_path = Path.home() / ".jiuwenclaw" / "config" / "builtin_rules.yaml"
+ fallback_user_path = get_config_dir() / "builtin_rules.yaml"
if fallback_user_path.is_file():
return fallback_user_path
pkg_path = _package_builtin_rules_path()
diff --git a/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/service.py b/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/service.py
index ef0cb849b2..b1f7305fde 100644
--- a/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/service.py
+++ b/jiuwenclaw/agentserver/tools/browser-move/src/playwright_runtime/service.py
@@ -35,10 +35,12 @@ from playwright_runtime.config import BrowserRunGuardrails, resolve_playwright_m
from playwright_runtime.drivers.managed_browser import ManagedBrowserDriver, _default_chrome_user_data_dir
from playwright_runtime.hooks import BrowserCancellationMiddleware, BrowserRunCancelled
from playwright_runtime.profiles import BrowserProfile, BrowserProfileStore
+
from jiuwenclaw.browser_timeout_policy import (
allow_short_timeout_override,
resolve_browser_task_timeout,
)
+from jiuwenclaw.utils import get_user_workspace_dir
MAX_ITERATION_MESSAGE = "Max iterations reached without completion"
@@ -166,7 +168,7 @@ class BrowserService:
configured = (os.getenv("BROWSER_RUNTIME_STATE_DIR") or "").strip()
if configured:
return Path(configured).expanduser()
- return Path.home() / ".jiuwenclaw" / "browser-move"
+ return get_user_workspace_dir() / "browser-move"
def _resolve_profile_store_path(self) -> Path:
configured = (os.getenv("BROWSER_PROFILE_STORE_PATH") or "").strip()
diff --git a/jiuwenclaw/agentserver/tools/browser_start_client.py b/jiuwenclaw/agentserver/tools/browser_start_client.py
index d1ba55f342..152f98809d 100644
--- a/jiuwenclaw/agentserver/tools/browser_start_client.py
+++ b/jiuwenclaw/agentserver/tools/browser_start_client.py
@@ -37,6 +37,8 @@ from openjiuwen.harness.tools.browser_move.playwright_runtime.profiles import (
BrowserProfileStore,
)
+from jiuwenclaw.utils import get_user_workspace_dir
+
logger = logging.getLogger(__name__)
@@ -56,7 +58,7 @@ def _browser_runtime_state_root() -> Path:
configured = (os.getenv("BROWSER_RUNTIME_STATE_DIR") or "").strip()
if configured:
return Path(configured).expanduser()
- return Path.home() / ".jiuwenclaw"
+ return get_user_workspace_dir()
def _profile_store_path() -> Path:
diff --git a/jiuwenclaw/agentserver/tools/task_tools.py b/jiuwenclaw/agentserver/tools/task_tools.py
index 15567f42fe..d9eaa10cb1 100644
--- a/jiuwenclaw/agentserver/tools/task_tools.py
+++ b/jiuwenclaw/agentserver/tools/task_tools.py
@@ -16,7 +16,7 @@ from jiuwenclaw.agentserver.tools import (
tool,
)
-from jiuwenclaw.utils import get_user_workspace_dir
+from jiuwenclaw.utils import get_agent_workspace_dir
logger = logging.getLogger(__name__)
@@ -36,7 +36,7 @@ class TaskAddParams:
# Path for persisting task_add entries
def _get_task_data_path() -> str:
- return str(get_user_workspace_dir() / "agent" / "workspace" / "task-data.json")
+ return str(get_agent_workspace_dir() / "task-data.json")
_connector = JSONFileConnector(indent=2)
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index eb45cf26ad..3e34790e5f 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -3,6 +3,8 @@
Runs ``jiuwenclaw.app_agentserver`` then ``jiuwenclaw.app_gateway`` with the same
environment as a normal CLI launch. Web RPC handlers live in ``app_web_handlers``.
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
"""
from __future__ import annotations
@@ -13,6 +15,11 @@ import time
from dotenv import load_dotenv
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early, get_parsed_dotenv
+parse_dotenv_early("jiuwenclaw-app")
+
+# --- Now safe to import jiuwenclaw modules ---
from jiuwenclaw.utils import (
cleanup_team_files,
get_env_file,
@@ -21,6 +28,9 @@ from jiuwenclaw.utils import (
reset_free_search_runtime_flags,
)
+# Record the parsed dotenv path for subprocess spawning
+_parsed_dotenv_path = get_parsed_dotenv()
+
_workspace_dir = get_user_workspace_dir()
_config_file = _workspace_dir / "config" / "config.yaml"
@@ -39,13 +49,47 @@ reset_free_search_runtime_flags()
def main() -> None:
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ prog="jiuwenclaw-app",
+ description="Start JiuWenClaw AgentServer + Gateway (split layout, one command).",
+ )
+ parser.add_argument(
+ "--dotenv",
+ metavar="<path>",
+ help="Load environment from .env file (processed at startup, not used here).",
+ )
+ parser.add_argument(
+ "--name",
+ metavar="<name>",
+ help="Start a named instance from instances.yaml.",
+ )
+ args = parser.parse_args()
+
+ # Handle --name: check if bootstrap .env was loaded successfully
+ # (parse_dotenv_early() already processed it at module import time)
+ dotenv_path = _parsed_dotenv_path
+ if args.name and dotenv_path is None:
+ # Early parsing failed - error was already printed
+ raise SystemExit(1)
+
python = sys.executable
- agent = subprocess.Popen([python, "-m", "jiuwenclaw.app_agentserver"])
+ # Build subprocess commands with --dotenv if parsed
+ agent_cmd = [python, "-m", "jiuwenclaw.app_agentserver"]
+ gateway_cmd = [python, "-m", "jiuwenclaw.app_gateway"]
+
+ # Pass --dotenv to subprocesses for multi-instance isolation
+ if dotenv_path is not None:
+ agent_cmd.extend(["--dotenv", str(dotenv_path)])
+ gateway_cmd.extend(["--dotenv", str(dotenv_path)])
+
+ agent = subprocess.Popen(agent_cmd)
gateway = None
try:
time.sleep(0.4)
- gateway = subprocess.Popen([python, "-m", "jiuwenclaw.app_gateway"])
+ gateway = subprocess.Popen(gateway_cmd)
except Exception:
if agent.poll() is None:
agent.terminate()
diff --git a/jiuwenclaw/app_agentserver.py b/jiuwenclaw/app_agentserver.py
index 79fda0dda2..7751fd3286 100644
--- a/jiuwenclaw/app_agentserver.py
+++ b/jiuwenclaw/app_agentserver.py
@@ -7,6 +7,8 @@ This process only starts:
Gateway should be started separately and connect to this ws server.
Both processes share the same user workspace directory (~/.jiuwenclaw).
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
"""
from __future__ import annotations
@@ -15,10 +17,16 @@ import argparse
import asyncio
import logging
import os
+import sys
from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early
+parse_dotenv_early("jiuwenclaw-agentserver")
+
+# --- Now safe to import jiuwenclaw modules ---
from jiuwenclaw.utils import (
get_env_file,
get_user_workspace_dir,
@@ -111,6 +119,8 @@ async def _run(host: str, port: int) -> None:
def main() -> None:
+ from jiuwenclaw.dotenv_early import get_parsed_dotenv
+
parser = argparse.ArgumentParser(
prog="jiuwenclaw-agentserver",
description="Start JiuwenClaw AgentServer (standalone process for Gateway to connect).",
@@ -123,8 +133,24 @@ def main() -> None:
metavar="PORT",
help="Bind port (default: AGENT_SERVER_PORT env or 18092).",
)
+ parser.add_argument(
+ "--name",
+ metavar="<name>",
+ help="Start a named instance from instances.yaml.",
+ )
+ parser.add_argument(
+ "--dotenv",
+ metavar="<path>",
+ help="Load environment from .env file (processed at startup, not used here).",
+ )
args = parser.parse_args()
+ # Handle --name: check if bootstrap .env was loaded successfully
+ # (parse_dotenv_early() already processed it at module import time)
+ if args.name and get_parsed_dotenv() is None:
+ # Early parsing failed - error was already printed
+ raise SystemExit(1)
+
host = os.getenv("AGENT_SERVER_HOST", "0.0.0.0")
port = args.port
if port is None:
diff --git a/jiuwenclaw/app_cli.py b/jiuwenclaw/app_cli.py
index 70c7ed7814..2bd8dd6c89 100644
--- a/jiuwenclaw/app_cli.py
+++ b/jiuwenclaw/app_cli.py
@@ -1,5 +1,10 @@
from __future__ import annotations
+"""JiuWenClaw CLI entrypoint (subcommand dispatcher).
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
+"""
+
import argparse
import json
import logging
@@ -8,6 +13,11 @@ import subprocess
import sys
import uuid
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early, get_parsed_dotenv
+parse_dotenv_early("jiuwenclaw-cli")
+
+# --- Now safe to import jiuwenclaw modules ---
from jiuwenclaw.e2a.adapters import (
e2a_response_to_acp_jsonrpc_response,
envelope_from_acp_jsonrpc,
@@ -17,6 +27,9 @@ from jiuwenclaw.e2a.models import E2AResponse
logger = logging.getLogger(__name__)
+# Record the parsed dotenv path for subprocess spawning
+_parsed_dotenv_path = get_parsed_dotenv()
+
def write_json_stdout(payload: dict) -> None:
sys.stdout.buffer.write((json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))
@@ -71,6 +84,10 @@ def run_acp(args: argparse.Namespace) -> int:
if gateway_url:
cmd.extend(["--gateway-url", str(gateway_url)])
+ # Pass --dotenv to subprocess for multi-instance isolation
+ if _parsed_dotenv_path is not None:
+ cmd.extend(["--dotenv", str(_parsed_dotenv_path)])
+
logger.info("[CLI] starting ACP stdio gateway: %s", cmd)
child_env = dict(os.environ)
child_env["PYTHONIOENCODING"] = "utf-8"
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index 13c165f3c0..dbe7835510 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -8,6 +8,8 @@ This process starts:
- Cron scheduler service (triggers remote AgentServer via ws)
It connects to a remote/local AgentServer WebSocket endpoint.
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
"""
from __future__ import annotations
@@ -27,6 +29,11 @@ from urllib.parse import urlparse
from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early
+parse_dotenv_early("jiuwenclaw-gateway")
+
+# --- Now safe to import jiuwenclaw modules ---
import jiuwenclaw.channel.acp_channel as acp_channel_module
from jiuwenclaw.channel.acp_channel import AcpGatewayBridge
from jiuwenclaw.gateway.route_binding import GatewayRouteBinding
@@ -1632,6 +1639,8 @@ async def _run(
def main() -> None:
+ from jiuwenclaw.dotenv_early import get_parsed_dotenv
+
parser = argparse.ArgumentParser(
prog="jiuwenclaw-gateway",
description="Start JiuwenClaw Gateway + Channels (split deployment; connects to jiuwenclaw-agentserver).",
@@ -1664,8 +1673,26 @@ def main() -> None:
metavar="PATH",
help="WebChannel ws path (default: WEB_PATH or /ws).",
)
+ parser.add_argument(
+ "--name",
+ metavar="<name>",
+ help="Start a named instance from instances.yaml.",
+ )
+ parser.add_argument(
+ "--dotenv",
+ metavar="<path>",
+ help="Load environment from .env file (processed at startup, not used here).",
+ )
args = parser.parse_args()
+ # Handle --name: check if bootstrap .env was loaded successfully
+ # (parse_dotenv_early() already processed it, this is just a fallback check)
+ if args.name:
+ if get_parsed_dotenv() is None:
+ # Early parsing failed - instance not found or workspace missing
+ # Error was already printed by parse_dotenv_early()
+ raise SystemExit(1)
+
default_host = os.getenv("AGENT_SERVER_HOST", "127.0.0.1")
default_port = os.getenv("AGENT_SERVER_PORT") or os.getenv("AGENT_PORT", "18092")
agent_server_url = (
diff --git a/jiuwenclaw/app_web.py b/jiuwenclaw/app_web.py
index 2cbd88d899..ae942477c1 100644
--- a/jiuwenclaw/app_web.py
+++ b/jiuwenclaw/app_web.py
@@ -1,6 +1,9 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""Serve built frontend static files with optional reverse proxy."""
+"""Serve built frontend static files with optional reverse proxy.
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
+"""
from __future__ import annotations
@@ -13,12 +16,18 @@ import os
import select
import socket
import ssl
+import sys
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlparse
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early
+parse_dotenv_early("jiuwenclaw-web")
+
+# --- Now safe to import jiuwenclaw modules ---
from jiuwenclaw.agentserver.tools.ssl_config import get_insecure_ssl_context, get_ssl_verify
from jiuwenclaw.utils import get_agent_root_dir, get_logs_dir, \
get_root_dir, get_user_workspace_dir, is_package_installation
@@ -788,9 +797,31 @@ def _setup_logger(logs_root: Path, log_level: str) -> logging.Logger:
def main() -> None:
+ from jiuwenclaw.dotenv_early import get_parsed_dotenv
+
+ # Check if --name bootstrap .env was loaded successfully
+ # (parse_dotenv_early() already processed it at module import time)
+ # This is just a fallback check for error handling
+ _early_name = None
+ for i, arg in enumerate(sys.argv):
+ if arg == "--name" and i + 1 < len(sys.argv):
+ _early_name = sys.argv[i + 1]
+
+ if _early_name and get_parsed_dotenv() is None:
+ # Early parsing failed - error was already printed
+ raise SystemExit(1)
+
+ # Read defaults from environment variables (for multi-instance support)
+ # FRONTEND_PORT is used for this HTTP static server
+ # WEB_PORT is the WebChannel websocket endpoint that this server proxies to
+ default_host = os.getenv("FRONTEND_HOST", "localhost")
+ default_port = int(os.getenv("FRONTEND_PORT", "5173"))
+ web_port = os.getenv("WEB_PORT", "19000") # WebChannel websocket port (proxy target)
+ default_proxy = os.getenv("GATEWAY_URL", f"http://127.0.0.1:{web_port}")
+
parser = argparse.ArgumentParser(description="Serve JiuwenClaw frontend static files.")
- parser.add_argument("--host", default="localhost", help="Host to bind.")
- parser.add_argument("--port", type=int, default=5173, help="Port to bind.")
+ parser.add_argument("--host", default=default_host, help="Host to bind.")
+ parser.add_argument("--port", type=int, default=default_port, help="Port to bind.")
parser.add_argument(
"--dist",
default=str(_default_dist_dir()),
@@ -798,7 +829,7 @@ def main() -> None:
)
parser.add_argument(
"--proxy-target",
- default="http://127.0.0.1:19000",
+ default=default_proxy,
help="Backend base URL for proxy (used as default for api/ws).",
)
parser.add_argument(
@@ -821,6 +852,16 @@ def main() -> None:
action="store_true",
help="Disable websocket compression for easier ws req/res/event debug logging.",
)
+ parser.add_argument(
+ "--name",
+ metavar="<name>",
+ help="Start a named instance from instances.yaml.",
+ )
+ parser.add_argument(
+ "--dotenv",
+ metavar="<path>",
+ help="Load environment from .env file (processed at startup, not used here).",
+ )
args = parser.parse_args()
dist_dir = Path(args.dist).expanduser().resolve()
diff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.py
index 643fcf9483..071cf2bf5a 100644
--- a/jiuwenclaw/channel/acp_channel.py
+++ b/jiuwenclaw/channel/acp_channel.py
@@ -11,6 +11,11 @@ import uuid
from dataclasses import dataclass, field
from typing import Any, Callable
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early
+parse_dotenv_early("jiuwenclaw-acp-channel")
+
+# --- Now safe to import jiuwenclaw modules ---
from jiuwenclaw.channel.base import BaseChannel, RobotMessageRouter
from jiuwenclaw.e2a.acp.protocol import (
build_acp_initialize_result,
diff --git a/jiuwenclaw/channel/dingding.py b/jiuwenclaw/channel/dingding.py
index d19080223a..f8da5fc6f1 100644
--- a/jiuwenclaw/channel/dingding.py
+++ b/jiuwenclaw/channel/dingding.py
@@ -16,6 +16,7 @@ import httpx
from jiuwenclaw.channel.base import RobotMessageRouter, BaseChannel
from jiuwenclaw.channel.dingtalk_file_service import DingTalkFileService
from jiuwenclaw.schema.message import Message, ReqMethod
+from jiuwenclaw.utils import get_agent_workspace_dir
logger = logging.getLogger(__name__)
@@ -354,7 +355,7 @@ class DingTalkChannel(BaseChannel):
self._http = httpx.AsyncClient()
# 初始化文件服务
- workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")
+ workspace_dir = self.config.workspace_dir or str(get_agent_workspace_dir())
self._file_service = DingTalkFileService(
client_id=self.config.client_id,
get_token_func=self._get_access_token,
@@ -1088,7 +1089,7 @@ class DingTalkChannel(BaseChannel):
if not self._file_service or not self.config.send_file_allowed:
return
- workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")
+ workspace_dir = self.config.workspace_dir or str(get_agent_workspace_dir())
if not os.path.isdir(workspace_dir):
return
diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.py
index dd556d0a7d..4345cdfa90 100644
--- a/jiuwenclaw/channel/feishu.py
+++ b/jiuwenclaw/channel/feishu.py
@@ -1558,9 +1558,10 @@ class FeishuChannel(BaseChannel):
seen: set[str] = set()
result: list[str] = []
- # 模式1:完整路径
- abs_pattern = r"(/home/[^\s\[\]\"']+\.jiuwenclaw/agent/workspace/[^\s\[\]\"']+\.\w+)"
- for m in re.findall(abs_pattern, text):
+ # 模式1:完整路径 - 动态匹配当前 workspace 目录
+ # 支持 Linux (/home/xxx/.jiuwenclaw/...) 和 Windows (C:\Users\xxx\.jiuwenclaw\...)
+ workspace_pattern = re.escape(workspace_dir) + r"[^\s\[\]\"']+\.\w+"
+ for m in re.findall(workspace_pattern, text):
m = m.rstrip(".,;:!?)")
if m not in seen and os.path.isfile(m):
seen.add(m)
diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.py
index 6e11e1fb0e..ce7eeed03a 100644
--- a/jiuwenclaw/channel/wecom_channel.py
+++ b/jiuwenclaw/channel/wecom_channel.py
@@ -21,6 +21,7 @@ from pydantic import BaseModel, Field
from jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouter
from jiuwenclaw.channel.platform_adapter.message import MessageStore
from jiuwenclaw.schema.message import Message, ReqMethod, EventType
+from jiuwenclaw.utils import get_agent_workspace_dir
logger = logging.getLogger(__name__)
@@ -1371,7 +1372,7 @@ class WecomChannel(BaseChannel):
# 初始化文件服务
try:
from jiuwenclaw.channel.wecom_file_service import WecomFileService
- workspace_dir = self.config.workspace_dir or os.path.expanduser("~/.jiuwenclaw/agent/workspace")
+ workspace_dir = self.config.workspace_dir or str(get_agent_workspace_dir())
self._file_service = WecomFileService(
ws_client=client,
max_download_size=self.config.max_download_size,
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index f340ac0b67..6cc0e09890 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -15,7 +15,7 @@ import yaml
logger = logging.getLogger(__name__)
from ruamel.yaml import YAML
-from jiuwenclaw.utils import JIUWENCLAW_DATA_DIR, get_config_file
+from jiuwenclaw.utils import get_config_dir, get_config_file
_CONFIG_MODULE_DIR = Path(__file__).parent
_CONFIG_YAML_PATH = get_config_file()
@@ -24,8 +24,8 @@ _CONFIG_YAML_PATH = get_config_file()
_user_config = os.getenv("JIUWENCLAW_CONFIG_DIR")
if _user_config:
_CONFIG_MODULE_DIR = Path(_user_config)
-elif (JIUWENCLAW_DATA_DIR / "config").exists():
- _CONFIG_MODULE_DIR = JIUWENCLAW_DATA_DIR / "config"
+elif get_config_dir().exists():
+ _CONFIG_MODULE_DIR = get_config_dir()
# Ensure config directory is in sys.path
if str(_CONFIG_MODULE_DIR) not in sys.path:
diff --git a/jiuwenclaw/dotenv_early.py b/jiuwenclaw/dotenv_early.py
new file mode 100644
index 0000000000..e63cacbcc1
--- /dev/null
+++ b/jiuwenclaw/dotenv_early.py
@@ -0,0 +1,240 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Early --dotenv/--name parsing for multi-instance isolation.
+
+This module MUST be imported BEFORE any other jiuwenclaw modules,
+because it sets JIUWENCLAW_DATA_DIR environment variable that affects
+path resolution in jiuwenclaw.utils.
+
+Usage in entry point files:
+ from jiuwenclaw.dotenv_early import parse_dotenv_early
+ parse_dotenv_early()
+
+ # Now safe to import other jiuwenclaw modules
+ from jiuwenclaw.utils import ...
+
+The parsing happens before any jiuwenclaw imports:
+- sys.argv is scanned for --dotenv <path> and --name <name>
+- If --dotenv found: load that file
+- If --name found (no --dotenv): load instance bootstrap .env
+- JIUWENCLAW_DATA_DIR is injected into os.environ
+- Then get_user_workspace_dir() returns the correct instance path
+
+IMPORTANT: This ensures module-level code uses correct workspace path.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+from pathlib import Path
+
+# Early logger for startup diagnostics (outputs to stderr)
+_early_logger = logging.getLogger("jiuwenclaw.early")
+if not _early_logger.handlers:
+ _early_logger.addHandler(logging.StreamHandler(sys.stderr))
+ _early_logger.setLevel(logging.WARNING)
+
+
+def _early_warning(component_name: str, message: str) -> None:
+ """Log early warning message to stderr."""
+ _early_logger.warning("[%s] %s", component_name, message)
+
+
+def _early_error(component_name: str, message: str) -> None:
+ """Log early error message to stderr."""
+ _early_logger.error("[%s] %s", component_name, message)
+
+
+def parse_dotenv_early(component_name: str = "jiuwenclaw") -> Path | None:
+ """Parse --dotenv/--name arguments and load env before jiuwenclaw imports.
+
+ This function scans sys.argv for '--dotenv <path>' and '--name <name>' patterns,
+ and loads the appropriate .env file with override=True.
+
+ NOTE: This function does NOT remove arguments from sys.argv.
+ - argparse will still see and parse them normally
+ - But JIUWENCLAW_DATA_DIR is set BEFORE module-level code executes
+
+ Priority:
+ 1. --dotenv <path>: Use specified file directly
+ 2. --name <name>: Load instance bootstrap .env from instances.yaml
+
+ Args:
+ component_name: Name for warning messages (e.g., "jiuwenclaw-app")
+
+ Returns:
+ Path to the loaded .env file if found and loaded, None otherwise
+
+ Usage:
+ from jiuwenclaw.dotenv_early import parse_dotenv_early
+ parse_dotenv_early("jiuwenclaw-app")
+
+ # Now safe to import jiuwenclaw modules
+ from jiuwenclaw.utils import get_user_workspace_dir
+ """
+ global _parsed_dotenv, _component_name
+ _component_name = component_name
+ dotenv_path = None
+ name_value = None
+
+ # Scan sys.argv for --dotenv and --name patterns (DO NOT remove)
+ for i, arg in enumerate(sys.argv):
+ if arg == "--dotenv" and i + 1 < len(sys.argv):
+ dotenv_path = sys.argv[i + 1]
+ elif arg == "--name" and i + 1 < len(sys.argv):
+ name_value = sys.argv[i + 1]
+
+ # Load .env file
+ result: Path | None = None
+ if dotenv_path is not None:
+ # --dotenv takes priority
+ dotenv_file = Path(dotenv_path).expanduser().resolve()
+ if dotenv_file.exists():
+ from dotenv import load_dotenv
+ load_dotenv(dotenv_file, override=True)
+ result = dotenv_file
+ else:
+ _early_warning(component_name, f"--dotenv file not found: {dotenv_file}")
+
+ elif name_value is not None:
+ # --name: load instance bootstrap .env
+ result = _load_bootstrap_by_name_early(name_value, component_name)
+
+ # Store result for get_parsed_dotenv()
+ _parsed_dotenv = result
+ return result
+
+
+def _load_bootstrap_by_name_early(name: str, component_name: str) -> Path | None:
+ """Load bootstrap .env for named instance during early parsing.
+
+ This is called before any jiuwenclaw imports, so it needs to:
+ 1. Validate instance name (basic check, full validation later)
+ 2. Find instances.yaml and read instance workspace
+ 3. Load bootstrap .env if exists
+
+ Args:
+ name: Instance name
+ component_name: Component name for error messages
+
+ Returns:
+ Path to loaded .env if successful, None otherwise
+ """
+ import os
+
+ # Basic instance name validation (just check it's not empty/reserved)
+ if not name or name.lower() in ("default", "config", "tmp"):
+ _early_error(component_name, f"Invalid instance name '{name}'")
+ return None
+
+ # Find instances.yaml path (same logic as instance_manager but without imports)
+ user_home = os.environ.get("JIUWENCLAW_HOME") or Path.home()
+ yaml_path = Path(user_home) / ".jiuwenclaw" / "instances.yaml"
+
+ if not yaml_path.exists():
+ _early_error(component_name, f"instances.yaml not found: {yaml_path}")
+ _early_error(component_name, f"Run 'jiuwenclaw-init --name {name}' to create it.")
+ return None
+
+ # Parse YAML to find instance workspace (minimal parsing without full imports)
+ try:
+ import yaml
+ data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
+ instances = data.get("instances", {}) if data else {}
+
+ if name not in instances:
+ _early_error(component_name, f"Instance '{name}' not found in instances.yaml")
+ _early_error(component_name, f"Run 'jiuwenclaw-init --name {name}' to create it.")
+ return None
+
+ inst_data = instances.get(name) or {}
+ workspace_str = inst_data.get("workspace")
+
+ if workspace_str:
+ workspace = Path(workspace_str).expanduser().resolve()
+ else:
+ instances_dir = Path(user_home) / ".jiuwenclaw-instances"
+ workspace = instances_dir / name
+
+ except Exception as exc:
+ _early_error(component_name, f"Failed to parse instances.yaml: {exc}")
+ return None
+
+ # Check workspace exists
+ if not workspace.exists():
+ _early_error(component_name, f"Workspace directory not found: {workspace}")
+ _early_error(component_name, f"Run 'jiuwenclaw-init --name {name}' to create it.")
+ return None
+
+ # Load bootstrap .env
+ bootstrap_env = workspace / ".env"
+ if bootstrap_env.exists():
+ from dotenv import load_dotenv
+ load_dotenv(bootstrap_env, override=True)
+ return bootstrap_env
+ else:
+ # Bootstrap .env doesn't exist - need to create it
+ # Import bootstrap module (safe now that we're past early parsing)
+ from jiuwenclaw.instance_manager.bootstrap import _create_basic_bootstrap_env
+ _create_basic_bootstrap_env(name, workspace, component_name)
+ if bootstrap_env.exists():
+ from dotenv import load_dotenv
+ load_dotenv(bootstrap_env, override=True)
+ return bootstrap_env
+ return None
+
+
+# Self-contained early parsing (no function call needed)
+# This is the simplest usage pattern: just import this module
+# and the parsing happens automatically.
+_parsed_dotenv: Path | None = None
+_component_name: str = "jiuwenclaw"
+
+
+def set_component_name(name: str) -> None:
+ """Set the component name for warning messages.
+
+ Call this before importing the module if you want custom warnings:
+ from jiuwenclaw import dotenv_early
+ dotenv_early.set_component_name("jiuwenclaw-app")
+ # Now import triggers parsing with custom name
+
+ However, the simpler pattern is to just call parse_dotenv_early() directly.
+ """
+ global _component_name
+ _component_name = name
+
+
+def get_parsed_dotenv() -> Path | None:
+ """Get the path that was parsed, if any."""
+ return _parsed_dotenv
+
+
+def load_instance_bootstrap_by_name(name: str) -> Path | None:
+ """Load bootstrap .env for a named instance after argparse parsing.
+
+ This function is a wrapper that delegates to
+ jiuwenclaw.instance_manager.bootstrap.load_instance_bootstrap_by_name.
+
+ NOTE: This function is deprecated. Use the function from
+ jiuwenclaw.instance_manager.bootstrap directly for new code.
+
+ Args:
+ name: Instance name (must exist in instances.yaml)
+
+ Returns:
+ Path to loaded .env if successful, None otherwise
+ """
+ from jiuwenclaw.instance_manager.bootstrap import (
+ load_instance_bootstrap_by_name as _load_bootstrap,
+ )
+ return _load_bootstrap(name)
+
+
+__all__ = [
+ "parse_dotenv_early",
+ "get_parsed_dotenv",
+ "set_component_name",
+ "load_instance_bootstrap_by_name",
+]
\ No newline at end of file
diff --git a/jiuwenclaw/gateway/im_pipeline/im_inbound.py b/jiuwenclaw/gateway/im_pipeline/im_inbound.py
index 3d72ad75c1..58fd94da12 100644
--- a/jiuwenclaw/gateway/im_pipeline/im_inbound.py
+++ b/jiuwenclaw/gateway/im_pipeline/im_inbound.py
@@ -17,7 +17,7 @@ from jiuwenclaw.config import _parse_custom_headers
from jiuwenclaw.gateway.interaction_context import PendingInteraction
from jiuwenclaw.schema.message import Message, ReqMethod
from jiuwenclaw.gateway.slash_command import CONTROL_MESSAGE_TEXTS
-from jiuwenclaw.utils import get_root_dir, logger
+from jiuwenclaw.utils import get_deepagent_user_md_path, logger
SYSTEM_PROMPT_TEMPLATE = """
你是{principal_name}的数字分身,活跃在即时通讯群聊中。当群里有其他用户发送与{principal_name}相关的消息时,你的任务是改写这条消息,使其更清晰、更完整,以便后续帮助{principal_name}生成恰当的回复。
@@ -145,7 +145,7 @@ class IMConversationProcessor:
self._user_profile_path = (
user_profile_path
if user_profile_path is not None
- else get_root_dir() / "workspace" / "agent" / "memory" / "USER.md"
+ else get_deepagent_user_md_path()
)
self._model_name, self._model_client_raw = self._load_model_config(model_name)
self._llm: Model | None = None
diff --git a/jiuwenclaw/init_workspace.py b/jiuwenclaw/init_workspace.py
index c3a4f94f57..665bb861fc 100644
--- a/jiuwenclaw/init_workspace.py
+++ b/jiuwenclaw/init_workspace.py
@@ -12,26 +12,109 @@
使用方式:
- jiuwenclaw-init -f: 强制清理,删除整个用户数据根目录后重新初始化
- jiuwenclaw-init: 保留原有数据,执行迁移合并
+- jiuwenclaw-init --name alice: 创建命名实例 alice
+- jiuwenclaw-init -f --name alice: 强制重建命名实例 alice
"""
from __future__ import annotations
import argparse
import logging
+import os
import sys
+from typing import Optional
-from jiuwenclaw.utils import init_user_workspace
+from jiuwenclaw.utils import get_user_home, init_user_workspace, get_user_workspace_dir
+from jiuwenclaw.instance_manager import (
+ create_bootstrap_env,
+ get_default_instance_status,
+ get_instance_config,
+ get_instance_status,
+ get_instance_workspace_path,
+ get_instance_index,
+ calculate_instance_ports,
+ update_instances_yaml,
+ validate_instance_name,
+ InstanceConfig,
+)
-def run_init(force: bool = False) -> int:
+def run_init(force: bool = False, name: Optional[str] = None) -> int:
+ """Run workspace initialization.
+
+ Args:
+ force: Force clean initialization, delete entire workspace before init
+ name: Named instance name (e.g., alice, bob)
+ """
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
+ # 1. Validate instance name if provided
+ if name:
+ validation_error = validate_instance_name(name)
+ if validation_error:
+ print(f"[jiuwenclaw-init] ERROR: {validation_error}")
+ return 1
+
+ # 2. Determine target workspace path and set env var
+ if name:
+ workspace_path = get_instance_workspace_path(name)
+ print(f"[jiuwenclaw-init] Creating instance: {name}")
+ print(f"[jiuwenclaw-init] Workspace: {workspace_path}")
+ else:
+ workspace_path = get_user_home() / ".jiuwenclaw"
+ print(f"[jiuwenclaw-init] Initializing default workspace")
+ print(f"[jiuwenclaw-init] Workspace: {workspace_path}")
+
+ # 3. Check if instance is running (for named instances, always check)
+ if name:
+ # For named instance, check if it's running
+ config = get_instance_config(name)
+ if config is None:
+ # Instance not in instances.yaml yet, use default config
+ workspace_path = get_instance_workspace_path(name)
+ ports = calculate_instance_ports(1) # Will be recalculated when added to yaml
+ config = InstanceConfig(name=name, workspace=workspace_path, ports=ports)
+
+ status = get_instance_status(config)
+ if status.running:
+ print(f"[jiuwenclaw-init] ERROR: Instance '{name}' is running (PID={status.pid}).")
+ print(f"[jiuwenclaw-init] Stop it first with: jiuwenclaw-start --stop {name}")
+ return 1
+ elif force:
+ # For default instance, use get_default_instance_status which includes port detection
+ status = get_default_instance_status()
+ if status.running:
+ print(f"[jiuwenclaw-init] ERROR: Default instance is running (PID={status.pid or '-'}).")
+ print(f"[jiuwenclaw-init] Stop it first with: jiuwenclaw-start --stop default")
+ return 1
+
+ # 4. Set environment variable, then call init_user_workspace
+ # (deletion and confirmation handled by init_user_workspace)
+ os.environ["JIUWENCLAW_DATA_DIR"] = str(workspace_path)
target = init_user_workspace(overwrite=force)
+
+ # 5. Post-init: create bootstrap .env and update instances.yaml for named instance
+ if name and target != "cancelled":
+ # Calculate ports (using same index as update_instances_yaml will use)
+ index = get_instance_index(name)
+ ports = calculate_instance_ports(index)
+
+ # Update YAML with full configuration (workspace + ports)
+ update_instances_yaml(name, workspace_path, ports)
+
+ # Create bootstrap .env with the same ports
+ config = InstanceConfig(name=name, workspace=workspace_path, ports=ports)
+ create_bootstrap_env(config)
+
+ print(f"[jiuwenclaw-init] Instance '{name}' initialized successfully.")
+ return 0
+
if target == "cancelled":
return 1
+
print(f"[jiuwenclaw-init] initialized: {target}")
return 0
@@ -44,12 +127,18 @@ def main() -> int:
"-f",
"--force",
action="store_true",
- help="Force clean initialization: delete entire ~/.jiuwenclaw before init",
+ help="Force clean initialization: delete entire workspace before init",
+ )
+ parser.add_argument(
+ "--name",
+ type=str,
+ default=None,
+ help="Create a named instance workspace (e.g., alice, bob)",
)
# Use parse_known_args so that calling main() under pytest (which leaves
# test paths in sys.argv) does not fail with SystemExit on unknown args.
args, _ = parser.parse_known_args()
- return run_init(force=args.force)
+ return run_init(force=args.force, name=args.name)
if __name__ == "__main__":
diff --git a/jiuwenclaw/instance_manager/__init__.py b/jiuwenclaw/instance_manager/__init__.py
new file mode 100644
index 0000000000..a8a9189a69
--- /dev/null
+++ b/jiuwenclaw/instance_manager/__init__.py
@@ -0,0 +1,150 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Instance manager for multi-instance isolation.
+
+Provides utilities for:
+- Instance name validation
+- instances.yaml configuration management
+- Bootstrap .env file creation
+- Port allocation and conflict detection
+- PID file management
+- Instance status querying
+- Instance startup locking for concurrency safety
+
+Design reference: multi-instance-isolation-design.md
+
+This package is organized into submodules:
+- config: Data classes, constants, name validation, port management
+- yaml: YAML configuration parsing and writing
+- lock: Instance lock and PID file management
+- status: Status query, config loading, process control
+- bootstrap: Bootstrap .env creation
+
+All public APIs are re-exported from this module for backward compatibility.
+"""
+
+from __future__ import annotations
+
+# Data classes and constants from config
+from jiuwenclaw.instance_manager.config import (
+ InstanceConfig,
+ InstanceStatus,
+ InstancesYamlError,
+ BASE_PORTS,
+ INSTANCE_NAME_PATTERN,
+ PID_FILENAME,
+ PORT_TYPES,
+ RESERVED_NAMES,
+)
+
+# Name validation from config
+from jiuwenclaw.instance_manager.config import (
+ is_valid_instance_name,
+ validate_instance_name,
+)
+
+# Port management from config
+from jiuwenclaw.instance_manager.config import (
+ calculate_instance_ports,
+ check_port_conflicts,
+ collect_all_ports,
+ compute_auto_port,
+ is_port_available,
+)
+
+# YAML management from yaml
+from jiuwenclaw.instance_manager.yaml import (
+ create_instances_yaml_template,
+ get_instance_index,
+ get_instance_workspace_path,
+ get_instances_dir,
+ get_instances_yaml_path,
+ load_instances_yaml,
+ save_instances_yaml,
+ update_instances_yaml,
+)
+
+# Instance lock and PID management from lock
+from jiuwenclaw.instance_manager.lock import (
+ InstanceLock,
+ LOCK_FILENAME,
+ STALE_LOCK_TIMEOUT,
+ check_instance_running,
+ delete_pid_file,
+ is_process_alive,
+ read_pid_file,
+ write_pid_file,
+)
+
+# Status query and process control from status
+from jiuwenclaw.instance_manager.status import (
+ format_status_line,
+ get_default_instance_status,
+ get_instance_config,
+ get_instance_status,
+ list_all_instances,
+ load_all_instance_configs,
+ stop_instance_process,
+ stop_process_by_pid,
+)
+
+# Bootstrap .env creation from bootstrap
+from jiuwenclaw.instance_manager.bootstrap import (
+ create_bootstrap_env,
+ create_bootstrap_env_for_name,
+ load_instance_bootstrap_by_name,
+)
+
+__all__ = [
+ # Data classes
+ "InstanceConfig",
+ "InstanceStatus",
+ "InstancesYamlError",
+ # Constants
+ "BASE_PORTS",
+ "INSTANCE_NAME_PATTERN",
+ "PID_FILENAME",
+ "PORT_TYPES",
+ "RESERVED_NAMES",
+ "LOCK_FILENAME",
+ "STALE_LOCK_TIMEOUT",
+ # Name validation
+ "validate_instance_name",
+ "is_valid_instance_name",
+ # Port management
+ "compute_auto_port",
+ "calculate_instance_ports",
+ "is_port_available",
+ "check_port_conflicts",
+ "collect_all_ports",
+ # YAML management
+ "get_instances_yaml_path",
+ "get_instances_dir",
+ "get_instance_workspace_path",
+ "load_instances_yaml",
+ "save_instances_yaml",
+ "create_instances_yaml_template",
+ "update_instances_yaml",
+ "get_instance_index",
+ # Instance lock and PID
+ "InstanceLock",
+ "write_pid_file",
+ "read_pid_file",
+ "delete_pid_file",
+ "is_process_alive",
+ "check_instance_running",
+ # Status query
+ "get_instance_status",
+ "get_default_instance_status",
+ "list_all_instances",
+ "format_status_line",
+ "get_instance_config",
+ "load_all_instance_configs",
+ # Process control
+ "stop_process_by_pid",
+ "stop_instance_process",
+ # Bootstrap .env
+ "create_bootstrap_env",
+ "create_bootstrap_env_for_name",
+ "load_instance_bootstrap_by_name",
+]
\ No newline at end of file
diff --git a/jiuwenclaw/instance_manager/bootstrap.py b/jiuwenclaw/instance_manager/bootstrap.py
new file mode 100644
index 0000000000..b71729ce9b
--- /dev/null
+++ b/jiuwenclaw/instance_manager/bootstrap.py
@@ -0,0 +1,202 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Bootstrap .env file creation for instances.
+
+This module provides:
+- create_bootstrap_env: Create bootstrap .env for an InstanceConfig
+- create_bootstrap_env_for_name: Create bootstrap .env for a named instance
+- _create_basic_bootstrap_env: Early-stage bootstrap creation (independent)
+- load_instance_bootstrap_by_name: Load bootstrap .env after argparse parsing
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from pathlib import Path
+
+import yaml
+
+from jiuwenclaw.instance_manager.config import (
+ InstanceConfig,
+ BASE_PORTS,
+ calculate_instance_ports,
+ validate_instance_name,
+)
+from jiuwenclaw.instance_manager.status import get_instance_config
+from jiuwenclaw.instance_manager.yaml import get_instance_index
+
+logger = logging.getLogger(__name__)
+
+
+def create_bootstrap_env(config: InstanceConfig) -> Path:
+ """Create bootstrap .env file for an instance.
+
+ The bootstrap .env contains:
+ - JIUWENCLAW_DATA_DIR: instance workspace path
+ - JIUWENCLAW_INSTANCE: instance name
+ - Port assignments for each service
+
+ Args:
+ config: InstanceConfig for the instance
+
+ Returns:
+ Path to the created .env file
+ """
+ env_path = config.get_bootstrap_env_path()
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+
+ lines = [
+ f"# Bootstrap .env for instance: {config.name}",
+ f"JIUWENCLAW_DATA_DIR={config.workspace}",
+ f"JIUWENCLAW_INSTANCE={config.name}",
+ ]
+
+ # Add port assignments
+ port_env_mapping = {
+ "agent_server": "AGENT_SERVER_PORT",
+ "web": "WEB_PORT",
+ "gateway": "GATEWAY_PORT",
+ "frontend": "FRONTEND_PORT",
+ }
+
+ for port_type, env_name in port_env_mapping.items():
+ if port_type in config.ports:
+ lines.append(f"{env_name}={config.ports[port_type]}")
+
+ env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ logger.info(
+ "Created bootstrap .env for instance '%s': %s", config.name, env_path
+ )
+ return env_path
+
+
+def create_bootstrap_env_for_name(name: str, workspace: Path) -> Path:
+ """Create bootstrap .env file for a named instance (legacy interface)."""
+ index = get_instance_index(name)
+ ports = calculate_instance_ports(index)
+ config = InstanceConfig(name=name, workspace=workspace, ports=ports)
+ return create_bootstrap_env(config)
+
+
+# --- Early-stage bootstrap functions (from dotenv_early.py) ---
+
+
+def _create_basic_bootstrap_env(
+ name: str, workspace: Path, component_name: str
+) -> None:
+ """Create a basic bootstrap .env file during early parsing.
+
+ This is needed when instance was created but bootstrap .env is missing.
+ Uses auto-port allocation based on instance index.
+
+ IMPORTANT: This function must NOT depend on any jiuwenclaw modules
+ because it is called during early parsing before any imports.
+
+ Args:
+ name: Instance name
+ workspace: Workspace path
+ component_name: Component name for logging
+ """
+ # Early logger for startup diagnostics
+ _early_logger = logging.getLogger("jiuwenclaw.early")
+ if not _early_logger.handlers:
+ import sys
+ _early_logger.addHandler(logging.StreamHandler(sys.stderr))
+ _early_logger.setLevel(logging.WARNING)
+
+ # Get instance index from instances.yaml order
+ user_home = os.environ.get("JIUWENCLAW_HOME") or Path.home()
+ yaml_path = Path(user_home) / ".jiuwenclaw" / "instances.yaml"
+
+ try:
+ data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
+ instances = list(data.get("instances", {}).keys()) if data else []
+ index = instances.index(name) + 1 if name in instances else 1
+ except Exception:
+ index = 1
+
+ # Auto-allocated ports (same logic as config.BASE_PORTS)
+ ports = {k: v + index * 1000 for k, v in BASE_PORTS.items()}
+
+ # Write bootstrap .env
+ bootstrap_env = workspace / ".env"
+ lines = [
+ f"# Bootstrap .env for instance: {name}",
+ f"JIUWENCLAW_DATA_DIR={workspace}",
+ f"JIUWENCLAW_INSTANCE={name}",
+ f"AGENT_SERVER_PORT={ports['agent_server']}",
+ f"WEB_PORT={ports['web']}",
+ f"GATEWAY_PORT={ports['gateway']}",
+ f"FRONTEND_PORT={ports['frontend']}",
+ ]
+ bootstrap_env.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ _early_logger.info(
+ "[%s] Created bootstrap .env: %s", component_name, bootstrap_env
+ )
+
+
+def load_instance_bootstrap_by_name(name: str) -> Path | None:
+ """Load bootstrap .env for a named instance after argparse parsing.
+
+ This function is called from CLI main() when --name is specified
+ but --dotenv was not parsed early. It loads the instance's bootstrap
+ .env file to set JIUWENCLAW_DATA_DIR and port environment variables.
+
+ Args:
+ name: Instance name (must exist in instances.yaml)
+
+ Returns:
+ Path to loaded .env if successful, None otherwise
+
+ Error handling:
+ - Invalid instance name: prints error and returns None
+ - Instance not in instances.yaml: prints error and returns None
+ - Workspace not found: prints error with init hint and returns None
+
+ Usage in CLI entry points:
+ def main():
+ parser.add_argument("--name", ...)
+ args = parser.parse_args()
+
+ if args.name:
+ from jiuwenclaw.instance_manager.bootstrap import (
+ load_instance_bootstrap_by_name
+ )
+ env_path = load_instance_bootstrap_by_name(args.name)
+ if env_path is None:
+ raise SystemExit(1)
+ """
+ _logger = logging.getLogger(__name__)
+
+ # Validate instance name
+ error = validate_instance_name(name)
+ if error:
+ _logger.error("ERROR: %s", error)
+ return None
+
+ # Load instance config from instances.yaml
+ config = get_instance_config(name)
+ if config is None:
+ _logger.error("ERROR: Instance '%s' not found in instances.yaml", name)
+ _logger.error("Run 'jiuwenclaw-init --name %s' to create it.", name)
+ return None
+
+ # Check workspace directory exists
+ if not config.workspace.exists():
+ _logger.error(
+ "ERROR: Workspace directory not found: %s", config.workspace
+ )
+ _logger.error("Run 'jiuwenclaw-init --name %s' to create it.", name)
+ return None
+
+ # Get or create bootstrap .env
+ env_path = config.get_bootstrap_env_path()
+ if not env_path.exists():
+ env_path = create_bootstrap_env(config)
+
+ # Load the .env file with override=True
+ from dotenv import load_dotenv
+ load_dotenv(env_path, override=True)
+
+ return env_path
\ No newline at end of file
diff --git a/jiuwenclaw/instance_manager/config.py b/jiuwenclaw/instance_manager/config.py
new file mode 100644
index 0000000000..2ee220f547
--- /dev/null
+++ b/jiuwenclaw/instance_manager/config.py
@@ -0,0 +1,265 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Instance configuration, constants, name validation, and port management.
+
+This module provides:
+- Data classes: InstanceConfig, InstanceStatus, InstancesYamlError
+- Constants: BASE_PORTS, PORT_TYPES, INSTANCE_NAME_PATTERN, RESERVED_NAMES
+- Name validation: validate_instance_name, is_valid_instance_name
+- Port management: compute_auto_port, calculate_instance_ports, is_port_available, etc.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import platform
+import re
+import socket
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Dict, List, Optional, Sequence
+
+logger = logging.getLogger(__name__)
+
+
+class InstancesYamlError(Exception):
+ """Custom exception for instances.yaml parsing/validation errors.
+
+ Provides user-friendly error messages with actionable fix suggestions.
+ """
+
+ def __init__(self, message: str):
+ # Prepend consistent header for CLI display
+ super().__init__(f"[instances.yaml] {message}")
+
+
+# Instance name validation rules
+INSTANCE_NAME_PATTERN = re.compile(r'^[a-zA-Z0-9_-]+$')
+RESERVED_NAMES = frozenset({'default', 'config', 'tmp', 'jiuwenclaw', 'all'})
+
+# Base ports for default instance (index=0)
+BASE_PORTS = {
+ "agent_server": 18092,
+ "web": 19000,
+ "gateway": 19001,
+ "frontend": 5173,
+}
+
+# Port types that must be unique across instances
+PORT_TYPES = ("agent_server", "web", "gateway", "frontend")
+
+# PID file name in workspace directory
+PID_FILENAME = ".instance.pid"
+
+
+@dataclass
+class InstanceConfig:
+ """Configuration for a named instance.
+
+ Attributes:
+ name: Instance name (unique identifier)
+ workspace: Path to instance workspace directory
+ ports: Dict of port assignments for each service type
+ """
+ name: str
+ workspace: Path
+ ports: Dict[str, int] = field(default_factory=dict)
+
+ def __post_init__(self) -> None:
+ """Expand and resolve workspace path."""
+ self.workspace = Path(self.workspace).expanduser().resolve()
+
+ def get_pid_file_path(self) -> Path:
+ """Get the PID file path for this instance."""
+ return self.workspace / PID_FILENAME
+
+ def get_bootstrap_env_path(self) -> Path:
+ """Get the bootstrap .env file path for this instance."""
+ return self.workspace / ".env"
+
+
+@dataclass
+class InstanceStatus:
+ """Runtime status of an instance.
+
+ Attributes:
+ name: Instance name
+ running: Whether the instance is currently running
+ pid: Process ID if running, None otherwise
+ workspace: Path to instance workspace
+ ports: Dict of port assignments
+ started_at: Startup timestamp if running, None otherwise
+ """
+ name: str
+ running: bool
+ pid: Optional[int]
+ workspace: Path
+ ports: Dict[str, int]
+ started_at: Optional[float] = None
+
+
+def validate_instance_name(name: str) -> Optional[str]:
+ """Validate instance name, return error message or None if valid.
+
+ Rules:
+ - Length: 1-64 characters
+ - Pattern: letters, digits, underscore, hyphen only
+ - No leading dot
+ - Not a reserved name
+ """
+ if not name or not isinstance(name, str):
+ return "Instance name must be a non-empty string"
+ if len(name) < 1 or len(name) > 64:
+ return "Instance name must be 1-64 characters"
+ if not INSTANCE_NAME_PATTERN.match(name):
+ return "Instance name must contain only letters, digits, underscore, hyphen"
+ if name.startswith('.'):
+ return "Instance name cannot start with dot"
+ if name.lower() in RESERVED_NAMES:
+ return f"Instance name '{name}' is reserved"
+ return None
+
+
+def is_valid_instance_name(name: str) -> bool:
+ """Check if instance name is valid (returns bool)."""
+ return validate_instance_name(name) is None
+
+
+def compute_auto_port(port_type: str, index: int) -> int:
+ """Compute auto-allocated port for an instance.
+
+ Algorithm: base_port + index * 1000
+ - index 0 reserved for default instance
+ - Named instances start from index 1
+
+ Args:
+ port_type: Service type (agent_server, web, gateway, frontend)
+ index: Instance index (0 for default, 1+ for named)
+
+ Returns:
+ Computed port number
+ """
+ base = BASE_PORTS.get(port_type, 10000)
+ return base + index * 1000
+
+
+def calculate_instance_ports(index: int) -> Dict[str, int]:
+ """Calculate ports for an instance: base_port + index * 1000."""
+ return {k: v + index * 1000 for k, v in BASE_PORTS.items()}
+
+
+def is_port_available(host: str, port: int) -> bool:
+ """Check if a port is available on the given host.
+
+ Args:
+ host: Host address to check
+ port: Port number to check
+
+ Returns:
+ True if port is available, False if occupied
+ """
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.settimeout(0.5)
+ try:
+ sock.connect((host, port))
+ return False # Port is occupied
+ except OSError:
+ return True # Port is available
+
+
+def check_port_conflicts(
+ ports: Dict[str, int],
+ host: str = "127.0.0.1",
+ existing_ports: Optional[Sequence[int]] = None,
+) -> List[int]:
+ """Check for port conflicts.
+
+ Args:
+ ports: Dict of port assignments to check
+ host: Host address to check
+ existing_ports: Ports already used by other instances
+
+ Returns:
+ List of conflicting port numbers
+ """
+ conflicts: List[int] = []
+ check_set = set(existing_ports or [])
+
+ for port_type, port in ports.items():
+ if port in check_set:
+ conflicts.append(port)
+ continue
+ if not is_port_available(host, port):
+ conflicts.append(port)
+
+ return conflicts
+
+
+def collect_all_ports(exclude_name: Optional[str] = None) -> List[int]:
+ """Collect all ports used by all instances for conflict detection.
+
+ Args:
+ exclude_name: Instance name to exclude from collection
+
+ Returns:
+ List of port numbers used by other instances
+ """
+ # Import locally to avoid circular dependency
+ from jiuwenclaw.instance_manager.yaml import load_instances_yaml
+
+ ports: List[int] = []
+
+ # Default instance ports
+ if exclude_name != "default":
+ for port_type in PORT_TYPES:
+ ports.append(compute_auto_port(port_type, 0))
+
+ # Named instance ports from instances.yaml
+ try:
+ data = load_instances_yaml()
+ instances = data.get("instances", {})
+ for name, inst_data in instances.items():
+ if name == exclude_name:
+ continue
+ index = list(instances.keys()).index(name) + 1
+ ports_config = (inst_data or {}).get("ports", {})
+ for port_type in PORT_TYPES:
+ if port_type in ports_config:
+ ports.append(ports_config[port_type])
+ else:
+ ports.append(compute_auto_port(port_type, index))
+ except Exception as exc:
+ logger.debug(
+ "Failed to load instance ports from yaml (ignored): %s", exc
+ )
+
+ return ports
+
+
+def _get_system_executable(name: str) -> str:
+ """Get absolute path for system executable.
+
+ Uses System32 path on Windows for common system utilities.
+ Falls back to shutil.which() for cross-platform resolution.
+
+ Args:
+ name: Executable name (e.g., 'tasklist', 'netstat', 'lsof')
+
+ Returns:
+ Absolute path to executable, or name if not found
+ """
+ import shutil
+
+ system = platform.system().lower()
+ if system == "windows":
+ # Windows system executables are in System32
+ system32 = os.path.join(
+ os.environ.get("SystemRoot", "C:\\Windows"), "System32"
+ )
+ exe_path = os.path.join(system32, f"{name}.exe")
+ if os.path.exists(exe_path):
+ return exe_path
+ # Fallback to shutil.which for cross-platform resolution
+ resolved = shutil.which(name)
+ return resolved or name
\ No newline at end of file
diff --git a/jiuwenclaw/instance_manager/lock.py b/jiuwenclaw/instance_manager/lock.py
new file mode 100644
index 0000000000..7601e52501
--- /dev/null
+++ b/jiuwenclaw/instance_manager/lock.py
@@ -0,0 +1,340 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Instance lock and PID file management.
+
+This module provides:
+- InstanceLock: Cross-platform file lock for instance startup concurrency
+- PID management: write/read/delete PID files, process alive detection
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import platform
+import subprocess
+import time
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from jiuwenclaw.instance_manager.config import (
+ InstanceConfig,
+ PID_FILENAME,
+ _get_system_executable,
+)
+
+logger = logging.getLogger(__name__)
+
+# Lock filename for instance startup concurrency control
+LOCK_FILENAME = ".instance.lock"
+# Stale lock timeout in seconds (locks older than this are considered stale)
+STALE_LOCK_TIMEOUT = 30.0
+
+
+class InstanceLock:
+ """Cross-platform file lock for instance startup concurrency control.
+
+ Prevents race conditions when multiple processes attempt to start
+ the same instance simultaneously. Uses platform-specific locking:
+ - Unix: fcntl.flock (POSIX advisory lock)
+ - Windows: exclusive file creation with timestamp-based stale detection
+
+ Usage:
+ lock = InstanceLock(config)
+ if not lock.acquire(timeout=5.0):
+ print("Instance startup in progress")
+ return
+ try:
+ # Start instance...
+ write_pid_file(config, os.getpid())
+ finally:
+ lock.release()
+
+ Note:
+ The lock is advisory on Unix and uses file existence on Windows.
+ Always acquire before PID file operations to ensure consistency.
+ """
+
+ def __init__(self, config: InstanceConfig):
+ """Initialize lock for given instance.
+
+ Args:
+ config: InstanceConfig to lock
+ """
+ self.config = config
+ self.lock_path = config.workspace / LOCK_FILENAME
+ self._lock_file: Optional[Any] = None
+
+ def acquire(self, timeout: float = 5.0) -> bool:
+ """Acquire exclusive lock for instance startup.
+
+ Args:
+ timeout: Max seconds to wait for lock acquisition
+
+ Returns:
+ True if lock acquired, False if timeout/in use
+ """
+ self.lock_path.parent.mkdir(parents=True, exist_ok=True)
+
+ system = platform.system().lower()
+
+ if system == "windows":
+ return self._acquire_windows(timeout)
+ else:
+ return self._acquire_unix(timeout)
+
+ def release(self) -> None:
+ """Release the lock."""
+ if self._lock_file is not None:
+ try:
+ system = platform.system().lower()
+ if system != "windows":
+ # Unix: release flock
+ import fcntl
+ fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_UN)
+ self._lock_file.close()
+ except Exception as exc:
+ logger.debug("Lock release error (ignored): %s", exc)
+ finally:
+ self._lock_file = None
+
+ # On Windows, also remove the lock file
+ if system == "windows":
+ try:
+ if self.lock_path.exists():
+ self.lock_path.unlink()
+ except OSError as exc:
+ logger.debug("Lock file removal error (ignored): %s", exc)
+
+ def _acquire_unix(self, timeout: float) -> bool:
+ """Unix implementation using fcntl.flock."""
+ import fcntl
+
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ try:
+ self._lock_file = open(self.lock_path, 'w')
+ fcntl.flock(
+ self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB
+ )
+ # Write lock info for debugging
+ self._lock_file.write(f"{os.getpid()}\n{time.time()}\n")
+ self._lock_file.flush()
+ return True
+ except (IOError, OSError):
+ if self._lock_file is not None:
+ try:
+ self._lock_file.close()
+ except Exception as exc:
+ logger.debug(
+ "Lock file close error during retry (ignored): %s",
+ exc
+ )
+ self._lock_file = None
+ time.sleep(0.1)
+
+ return False
+
+ def _acquire_windows(self, timeout: float) -> bool:
+ """Windows implementation using exclusive file creation.
+
+ Since Windows doesn't have fcntl, we use exclusive file creation
+ combined with timestamp-based stale lock detection.
+ """
+ deadline = time.time() + timeout
+
+ while time.time() < deadline:
+ try:
+ # Try exclusive creation (fails if file exists)
+ self._lock_file = open(self.lock_path, 'x', encoding='utf-8')
+ # Write lock info
+ self._lock_file.write(f"{os.getpid()}\n{time.time()}\n")
+ self._lock_file.flush()
+ return True
+ except FileExistsError:
+ # Lock file exists - check if stale
+ if self._is_stale_lock():
+ self._remove_stale_lock()
+ continue
+ time.sleep(0.1)
+ except OSError:
+ # Other OS error (permissions, etc.)
+ time.sleep(0.1)
+
+ return False
+
+ def _is_stale_lock(self) -> bool:
+ """Check if existing lock file is stale (older than STALE_LOCK_TIMEOUT)."""
+ try:
+ stat = self.lock_path.stat()
+ age = time.time() - stat.st_mtime
+ return age > STALE_LOCK_TIMEOUT
+ except OSError:
+ return False
+
+ def _remove_stale_lock(self) -> None:
+ """Remove stale lock file."""
+ try:
+ self.lock_path.unlink()
+ logger.info("Removed stale lock file: %s", self.lock_path)
+ except OSError:
+ pass
+
+ def __enter__(self) -> "InstanceLock":
+ """Context manager entry."""
+ self.acquire()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
+ """Context manager exit."""
+ self.release()
+
+
+def write_pid_file(
+ config: InstanceConfig,
+ pid: int,
+ started_at: Optional[float] = None
+) -> None:
+ """Write PID file for a running instance.
+
+ File format (JSON):
+ {
+ "pid": <process_id>,
+ "started_at": <timestamp>,
+ "name": <instance_name>
+ }
+
+ Uses atomic write: write to temp file then rename.
+
+ Args:
+ config: InstanceConfig for the instance
+ pid: Process ID to write
+ started_at: Startup timestamp, defaults to current time
+ """
+ pid_path = config.get_pid_file_path()
+ if started_at is None:
+ started_at = time.time()
+
+ data = {
+ "pid": pid,
+ "started_at": started_at,
+ "name": config.name,
+ }
+
+ # Atomic write: temp file + rename
+ pid_path.parent.mkdir(parents=True, exist_ok=True)
+ temp_path = pid_path.with_suffix(".tmp")
+ temp_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
+
+ # On Windows, need to remove existing file first
+ if pid_path.exists():
+ pid_path.unlink()
+ temp_path.rename(pid_path)
+
+ logger.info(
+ "Wrote PID file for instance '%s': pid=%d, path=%s",
+ config.name, pid, pid_path
+ )
+
+
+def read_pid_file(config: InstanceConfig) -> Optional[Dict[str, Any]]:
+ """Read PID file for an instance.
+
+ Args:
+ config: InstanceConfig for the instance
+
+ Returns:
+ Dict with pid, started_at, name if file exists and valid, None otherwise
+ """
+ pid_path = config.get_pid_file_path()
+ if not pid_path.exists():
+ return None
+
+ try:
+ data = json.loads(pid_path.read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ return None
+ return data
+ except (json.JSONDecodeError, IOError):
+ return None
+
+
+def delete_pid_file(config: InstanceConfig) -> bool:
+ """Delete PID file for an instance.
+
+ Args:
+ config: InstanceConfig for the instance
+
+ Returns:
+ True if file was deleted, False if it didn't exist
+ """
+ pid_path = config.get_pid_file_path()
+ if not pid_path.exists():
+ return False
+ pid_path.unlink()
+ logger.info(
+ "Deleted PID file for instance '%s': %s", config.name, pid_path
+ )
+ return True
+
+
+def is_process_alive(pid: int) -> bool:
+ """Check if a process with given PID is alive.
+
+ Args:
+ pid: Process ID to check
+
+ Returns:
+ True if process is running, False otherwise
+ """
+ if pid <= 0:
+ return False
+
+ system = platform.system().lower()
+
+ if system == "windows":
+ try:
+ result = subprocess.run(
+ [
+ _get_system_executable("tasklist"),
+ "/FI", f"PID eq {pid}", "/NH"
+ ],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ # tasklist returns "INFO: No tasks are running..." if not found
+ return str(pid) in result.stdout and "INFO:" not in result.stdout
+ except Exception:
+ return False
+ else:
+ # Unix: send signal 0 to check existence
+ try:
+ os.kill(pid, 0)
+ return True
+ except OSError:
+ return False
+
+
+def check_instance_running(workspace: Path) -> bool:
+ """Check if instance is running via PID file (legacy interface).
+
+ Args:
+ workspace: Instance workspace path
+
+ Returns:
+ True if instance is running, False otherwise
+ """
+ pid_file = workspace / PID_FILENAME
+ if not pid_file.exists():
+ return False
+
+ try:
+ data = json.loads(pid_file.read_text(encoding="utf-8"))
+ pid = data.get("pid", 0)
+ if not isinstance(pid, int) or pid <= 0:
+ return False
+ return is_process_alive(pid)
+ except (json.JSONDecodeError, IOError):
+ return False
\ No newline at end of file
diff --git a/jiuwenclaw/instance_manager/status.py b/jiuwenclaw/instance_manager/status.py
new file mode 100644
index 0000000000..bd4405aef6
--- /dev/null
+++ b/jiuwenclaw/instance_manager/status.py
@@ -0,0 +1,457 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Instance status query and process control.
+
+This module provides:
+- Status query: get_instance_status, get_default_instance_status, list_all_instances
+- Formatting: format_status_line
+- Config loading: get_instance_config, load_all_instance_configs
+- Process control: stop_process_by_pid, stop_instance_process
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import platform
+import subprocess
+import time
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from jiuwenclaw.instance_manager.config import (
+ InstanceConfig,
+ InstanceStatus,
+ PORT_TYPES,
+ compute_auto_port,
+ _get_system_executable,
+)
+from jiuwenclaw.instance_manager.lock import (
+ delete_pid_file,
+ is_process_alive,
+ read_pid_file,
+)
+from jiuwenclaw.instance_manager.yaml import (
+ get_instance_workspace_path,
+ get_instances_yaml_path,
+ load_instances_yaml,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def get_instance_status(config: InstanceConfig) -> InstanceStatus:
+ """Get runtime status of an instance.
+
+ Args:
+ config: InstanceConfig for the instance
+
+ Returns:
+ InstanceStatus with current state
+ """
+ pid_data = read_pid_file(config)
+
+ if pid_data is None:
+ return InstanceStatus(
+ name=config.name,
+ running=False,
+ pid=None,
+ workspace=config.workspace,
+ ports=config.ports,
+ started_at=None,
+ )
+
+ pid = pid_data.get("pid", 0)
+ started_at = pid_data.get("started_at")
+
+ if not isinstance(pid, int) or pid <= 0:
+ running = False
+ else:
+ running = is_process_alive(pid)
+
+ return InstanceStatus(
+ name=config.name,
+ running=running,
+ pid=pid if running else None,
+ workspace=config.workspace,
+ ports=config.ports,
+ started_at=started_at if running else None,
+ )
+
+
+def get_default_instance_status() -> InstanceStatus:
+ """Get status of the default instance (workspace at ~/.jiuwenclaw).
+
+ The default instance uses base ports (index 0) and standard workspace.
+ For default instance, we check port availability to determine running status
+ since PID file management may not be used.
+
+ Returns:
+ InstanceStatus for default instance
+ """
+ from jiuwenclaw.utils import get_user_workspace_dir
+
+ workspace = get_user_workspace_dir()
+ ports = {pt: compute_auto_port(pt, 0) for pt in PORT_TYPES}
+
+ config = InstanceConfig(name="default", workspace=workspace, ports=ports)
+
+ # First check PID file (if exists from previous named start)
+ pid_data = read_pid_file(config)
+
+ running = False
+ pid = None
+ started_at = None
+
+ if pid_data is not None:
+ pid = pid_data.get("pid", 0)
+ started_at = pid_data.get("started_at")
+ if isinstance(pid, int) and pid > 0 and is_process_alive(pid):
+ running = True
+
+ # If not running via PID file, check port availability
+ # Default instance may be started without PID file management
+ if not running:
+ # Check if any of the main ports are occupied
+ from jiuwenclaw.instance_manager.config import is_port_available
+
+ for port_type in ["agent_server", "gateway", "frontend"]:
+ port_num = ports.get(port_type, 0)
+ if port_num > 0 and not is_port_available("127.0.0.1", port_num):
+ pid = _find_pid_by_port(port_num)
+ running = True
+ break
+
+ return InstanceStatus(
+ name="default",
+ running=running,
+ pid=pid if running else None,
+ workspace=workspace,
+ ports=ports,
+ started_at=started_at if running else None,
+ )
+
+
+def _find_pid_by_port(port: int) -> Optional[int]:
+ """Find process PID that is listening on the given port.
+
+ Args:
+ port: Port number to check
+
+ Returns:
+ PID if found, None otherwise
+ """
+ if port <= 0:
+ return None
+
+ system = platform.system().lower()
+
+ try:
+ if system == "windows":
+ # Use netstat to find PID
+ result = subprocess.run(
+ [
+ _get_system_executable("netstat"),
+ "-ano", "-p", "tcp"
+ ],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ # Look for lines like: "TCP 0.0.0.0:18092 0.0.0.0:0 LISTENING 12345"
+ # or: "TCP 127.0.0.1:18092 0.0.0.0:0 LISTENING 12345"
+ for line in result.stdout.splitlines():
+ if "LISTENING" in line:
+ # Check for both 0.0.0.0 and 127.0.0.1 bindings
+ if f"0.0.0.0:{port}" in line or f"127.0.0.1:{port}" in line:
+ parts = line.split()
+ if parts:
+ last_part = parts[-1]
+ try:
+ return int(last_part)
+ except ValueError:
+ # Not a valid PID, continue to next line
+ continue
+ else:
+ # Unix: use lsof or ss
+ try:
+ result = subprocess.run(
+ [
+ _get_system_executable("lsof"),
+ "-i", f":{port}", "-t"
+ ],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.stdout.strip():
+ return int(result.stdout.strip().split()[0])
+ except (subprocess.SubprocessError, ValueError) as exc:
+ logger.debug(
+ "lsof lookup failed for port %d (ignored): %s", port, exc
+ )
+ except Exception as exc:
+ logger.debug("PID lookup by port %d failed (ignored): %s", port, exc)
+
+ return None
+
+
+def list_all_instances(include_default: bool = True) -> List[InstanceStatus]:
+ """List status of all instances.
+
+ Args:
+ include_default: Whether to include default instance in the list
+
+ Returns:
+ List of InstanceStatus for all configured instances
+ """
+ statuses: List[InstanceStatus] = []
+
+ # Add default instance first
+ if include_default:
+ statuses.append(get_default_instance_status())
+
+ # Add named instances from instances.yaml
+ yaml_path = get_instances_yaml_path()
+ if yaml_path.exists():
+ try:
+ configs = load_all_instance_configs(yaml_path)
+ for name, config in configs.items():
+ statuses.append(get_instance_status(config))
+ except Exception as exc:
+ logger.warning("Failed to load instances.yaml: %s", exc)
+
+ return statuses
+
+
+def format_status_line(status: InstanceStatus) -> str:
+ """Format an instance status for display.
+
+ Args:
+ status: InstanceStatus to format
+
+ Returns:
+ Formatted string for display
+ """
+ name = status.name
+
+ if status.running:
+ state = "running"
+ pid_str = str(status.pid or "-")
+ else:
+ state = "stopped"
+ pid_str = "-"
+
+ workspace_str = str(status.workspace)
+
+ ports_str = "/".join(
+ str(status.ports.get(pt, 0)) for pt in PORT_TYPES if status.ports.get(pt)
+ )
+
+ return f"{name:<12} {state:<8} {pid_str:<7} {workspace_str:<40} {ports_str}"
+
+
+def get_instance_config(name: str) -> Optional[InstanceConfig]:
+ """Load instance configuration from instances.yaml.
+
+ Args:
+ name: Instance name to load
+
+ Returns:
+ InstanceConfig if instance exists, None otherwise
+ """
+ data = load_instances_yaml()
+ if name not in data.get("instances", {}):
+ return None
+
+ instance_data = data["instances"][name] or {}
+ instances = list(data.get("instances", {}).keys())
+ index = instances.index(name) + 1
+
+ # Determine workspace path
+ workspace_str = instance_data.get("workspace")
+ if workspace_str:
+ workspace = Path(workspace_str)
+ else:
+ workspace = get_instance_workspace_path(name)
+
+ # Determine ports
+ ports_config = instance_data.get("ports", {})
+ ports: Dict[str, int] = {}
+ for port_type in PORT_TYPES:
+ if port_type in ports_config:
+ ports[port_type] = ports_config[port_type]
+ else:
+ ports[port_type] = compute_auto_port(port_type, index)
+
+ return InstanceConfig(name=name, workspace=workspace, ports=ports)
+
+
+def load_all_instance_configs(
+ path: Optional[Path] = None
+) -> Dict[str, InstanceConfig]:
+ """Load all instance configurations from instances.yaml.
+
+ Args:
+ path: Path to instances.yaml, defaults to standard location
+
+ Returns:
+ Dict mapping instance name to InstanceConfig
+ """
+ if path is None:
+ path = get_instances_yaml_path()
+
+ if not path.exists():
+ return {}
+
+ data = load_instances_yaml()
+ instances_data = data.get("instances", {})
+
+ configs: Dict[str, InstanceConfig] = {}
+
+ for index, (name, inst_data) in enumerate(instances_data.items(), start=1):
+ # Determine workspace
+ workspace_raw = (inst_data or {}).get("workspace")
+ if workspace_raw:
+ workspace = Path(workspace_raw).expanduser()
+ else:
+ workspace = get_instance_workspace_path(name)
+
+ # Determine ports (auto-allocate if not specified)
+ ports_data = (inst_data or {}).get("ports", {})
+ ports: Dict[str, int] = {}
+ for port_type in PORT_TYPES:
+ if port_type in ports_data:
+ ports[port_type] = ports_data[port_type]
+ else:
+ ports[port_type] = compute_auto_port(port_type, index)
+
+ configs[name] = InstanceConfig(
+ name=name,
+ workspace=workspace,
+ ports=ports,
+ )
+
+ return configs
+
+
+def stop_process_by_pid(pid: int, timeout: float = 10.0) -> bool:
+ """Stop a process by its PID directly.
+
+ Args:
+ pid: Process ID to stop
+ timeout: Seconds to wait for graceful shutdown
+
+ Returns:
+ True if process stopped successfully, False otherwise
+ """
+ if pid <= 0:
+ return True
+
+ if not is_process_alive(pid):
+ logger.info("Process %d already dead", pid)
+ return True
+
+ system = platform.system().lower()
+ logger.info("Stopping process with PID %d", pid)
+
+ if system == "windows":
+ # Use taskkill to terminate process tree
+ try:
+ subprocess.run(
+ [
+ _get_system_executable("taskkill"),
+ "/PID", str(pid), "/T", "/F"
+ ],
+ capture_output=True,
+ timeout=timeout,
+ )
+ except Exception as exc:
+ logger.warning("taskkill failed for PID %d: %s", pid, exc)
+ else:
+ # Unix: SIGTERM then SIGKILL
+ try:
+ os.kill(pid, 15) # SIGTERM
+ time.sleep(2)
+ if is_process_alive(pid):
+ os.kill(pid, 9) # SIGKILL
+ except OSError as exc:
+ logger.warning("kill failed for PID %d: %s", pid, exc)
+
+ # Wait for process to exit
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if not is_process_alive(pid):
+ break
+ time.sleep(0.5)
+
+ logger.info("Process %d stopped", pid)
+ return True
+
+
+def stop_instance_process(config: InstanceConfig, timeout: float = 10.0) -> bool:
+ """Stop a running instance process.
+
+ Args:
+ config: InstanceConfig for the instance
+ timeout: Seconds to wait for graceful shutdown
+
+ Returns:
+ True if process stopped successfully, False otherwise
+ """
+ pid_data = read_pid_file(config)
+ if pid_data is None:
+ logger.info(
+ "No PID file found for instance '%s', already stopped", config.name
+ )
+ return True
+
+ pid = pid_data.get("pid", 0)
+ if not isinstance(pid, int) or pid <= 0:
+ delete_pid_file(config)
+ return True
+
+ if not is_process_alive(pid):
+ logger.info(
+ "Process %d already dead for instance '%s'", pid, config.name
+ )
+ delete_pid_file(config)
+ return True
+
+ system = platform.system().lower()
+ logger.info("Stopping instance '%s' with PID %d", config.name, pid)
+
+ if system == "windows":
+ # Use taskkill to terminate process tree
+ try:
+ subprocess.run(
+ [
+ _get_system_executable("taskkill"),
+ "/PID", str(pid), "/T", "/F"
+ ],
+ capture_output=True,
+ timeout=timeout,
+ )
+ except Exception as exc:
+ logger.warning("taskkill failed for PID %d: %s", pid, exc)
+ else:
+ # Unix: SIGTERM then SIGKILL
+ try:
+ os.kill(pid, 15) # SIGTERM
+ time.sleep(2)
+ if is_process_alive(pid):
+ os.kill(pid, 9) # SIGKILL
+ except OSError as exc:
+ logger.warning("kill failed for PID %d: %s", pid, exc)
+
+ # Wait for process to exit
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if not is_process_alive(pid):
+ break
+ time.sleep(0.5)
+
+ # Cleanup PID file
+ delete_pid_file(config)
+ logger.info("Instance '%s' stopped", config.name)
+ return True
\ No newline at end of file
diff --git a/jiuwenclaw/instance_manager/yaml.py b/jiuwenclaw/instance_manager/yaml.py
new file mode 100644
index 0000000000..0150e618ec
--- /dev/null
+++ b/jiuwenclaw/instance_manager/yaml.py
@@ -0,0 +1,309 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""YAML configuration management for instances.
+
+This module provides:
+- Path functions: get_instances_yaml_path, get_instances_dir, get_instance_workspace_path
+- YAML parsing: load_instances_yaml with validation
+- YAML writing: save_instances_yaml, update_instances_yaml, create_instances_yaml_template
+- Index lookup: get_instance_index
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from jiuwenclaw.instance_manager.config import (
+ InstancesYamlError,
+ PORT_TYPES,
+ validate_instance_name,
+)
+from jiuwenclaw.utils import get_user_home
+
+logger = logging.getLogger(__name__)
+
+
+def get_instances_yaml_path() -> Path:
+ """Return path to instances.yaml: ~/.jiuwenclaw/instances.yaml"""
+ return get_user_home() / ".jiuwenclaw" / "instances.yaml"
+
+
+def get_instances_dir() -> Path:
+ """Return base directory for named instance workspaces: ~/.jiuwenclaw-instances/"""
+ return get_user_home() / ".jiuwenclaw-instances"
+
+
+def get_instance_workspace_path(name: str) -> Path:
+ """Return workspace path for a named instance: ~/.jiuwenclaw-instances/<name>/"""
+ return get_instances_dir() / name
+
+
+def _read_yaml_file(path: Path) -> dict:
+ """Read and parse YAML file with error handling.
+
+ Returns:
+ Parsed YAML data
+
+ Raises:
+ InstancesYamlError: If file cannot be read or parsed
+ """
+ try:
+ with open(path, 'r', encoding='utf-8') as f:
+ content = f.read()
+ except IOError as exc:
+ raise InstancesYamlError(
+ f"Cannot read file: {exc}\n"
+ f" Path: {path}\n"
+ f" Please check file permissions."
+ ) from exc
+
+ try:
+ data = yaml.safe_load(content)
+ except yaml.YAMLError as exc:
+ raise InstancesYamlError(
+ f"YAML format error:\n"
+ f" {exc}\n"
+ f" Path: {path}\n"
+ f" Fix suggestions:\n"
+ f" - Check YAML syntax (indentation, quotes, colons)\n"
+ f" - Ensure no duplicate keys\n"
+ f" - Run 'jiuwenclaw-init' to recreate a valid template"
+ ) from exc
+
+ return data
+
+
+def _validate_yaml_structure(data: Any, path: Path) -> dict:
+ """Validate YAML top-level structure.
+
+ Returns:
+ Validated dict with 'instances' key
+
+ Raises:
+ InstancesYamlError: If structure is invalid
+ """
+ if data is None:
+ return {"instances": {}}
+
+ if not isinstance(data, dict):
+ raise InstancesYamlError(
+ f"Invalid structure: expected dict, got {type(data).__name__}\n"
+ f" Path: {path}\n"
+ f" The file should start with 'instances:' key."
+ )
+
+ if "instances" not in data:
+ raise InstancesYamlError(
+ f"Missing 'instances' key\n"
+ f" Path: {path}\n"
+ f" Add 'instances: {{}}' to create an empty configuration."
+ )
+
+ instances_data = data.get("instances")
+ if instances_data is None:
+ data["instances"] = {}
+
+ return data
+
+
+def _validate_instance_entry(name: str, inst_data: Any, path: Path) -> None:
+ """Validate a single instance entry in instances.yaml.
+
+ Note: YAML dict keys are always strings, so name type check is skipped.
+
+ Raises:
+ InstancesYamlError: If instance entry is invalid
+ """
+ # Validate instance name format
+ error = validate_instance_name(name)
+ if error:
+ raise InstancesYamlError(
+ f"Invalid instance name '{name}': {error}\n"
+ f" Path: {path}\n"
+ f" Name rules: 1-64 chars, alphanumeric/underscore/hyphen only, "
+ f"no leading dot, not reserved."
+ )
+
+ # Validate instance data structure
+ if inst_data is not None and not isinstance(inst_data, dict):
+ raise InstancesYamlError(
+ f"Instance '{name}' has invalid data: expected dict or null, "
+ f"got {type(inst_data).__name__}\n"
+ f" Path: {path}"
+ )
+
+ if inst_data is None:
+ return
+
+ # Validate ports
+ if "ports" in inst_data:
+ _validate_ports_config(name, inst_data["ports"], path)
+
+ # Validate workspace
+ if "workspace" in inst_data:
+ workspace = inst_data["workspace"]
+ if not isinstance(workspace, str):
+ raise InstancesYamlError(
+ f"Instance '{name}': 'workspace' must be a string path, "
+ f"got {type(workspace).__name__}\n"
+ f" Path: {path}"
+ )
+
+
+def _validate_ports_config(name: str, ports: Any, path: Path) -> None:
+ """Validate ports configuration for an instance.
+
+ Raises:
+ InstancesYamlError: If ports config is invalid
+ """
+ if not isinstance(ports, dict):
+ raise InstancesYamlError(
+ f"Instance '{name}': 'ports' must be a dict\n"
+ f" Path: {path}\n"
+ f" Example: ports: {{agent_server: 28092, web: 29000}}"
+ )
+
+ for port_type, port_val in ports.items():
+ if port_type not in PORT_TYPES:
+ raise InstancesYamlError(
+ f"Instance '{name}': unknown port type '{port_type}'\n"
+ f" Valid types: {', '.join(PORT_TYPES)}\n"
+ f" Path: {path}"
+ )
+
+ if not isinstance(port_val, int):
+ raise InstancesYamlError(
+ f"Instance '{name}': port '{port_type}' must be integer, "
+ f"got {type(port_val).__name__}\n"
+ f" Path: {path}"
+ )
+
+ if port_val < 1 or port_val > 65535:
+ raise InstancesYamlError(
+ f"Instance '{name}': port '{port_type}' must be 1-65535, "
+ f"got {port_val}\n"
+ f" Path: {path}"
+ )
+
+
+def load_instances_yaml() -> dict:
+ """Load instances.yaml with comprehensive error handling.
+
+ Returns:
+ Dict with 'instances' key containing instance configurations
+
+ Raises:
+ InstancesYamlError: If file cannot be read, parsed, or validated
+ with user-friendly message and fix suggestions
+ """
+ path = get_instances_yaml_path()
+ if not path.exists():
+ return {"instances": {}}
+
+ # Read and parse YAML
+ data = _read_yaml_file(path)
+
+ # Validate structure
+ data = _validate_yaml_structure(data, path)
+
+ # Validate each instance entry
+ instances_data = data.get("instances", {})
+ for name, inst_data in instances_data.items():
+ _validate_instance_entry(name, inst_data, path)
+
+ return data
+
+
+def save_instances_yaml(data: dict) -> None:
+ """Save instances.yaml file."""
+ path = get_instances_yaml_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, 'w', encoding='utf-8') as f:
+ yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True)
+
+
+def create_instances_yaml_template() -> Path:
+ """Create a minimal instances.yaml template file if not exists."""
+ path = get_instances_yaml_path()
+ if path.exists():
+ return path
+
+ template = """# JiuWenClaw instances configuration
+# Each instance has its own workspace, ports, and processes
+#
+# Example:
+# instances:
+# alice:
+# # workspace: /custom/path/alice # optional, defaults to ~/.jiuwenclaw-instances/alice
+# ports:
+# agent_server: 28092
+# web: 29000
+# gateway: 29001
+# frontend: 29173
+# bob: # minimal declaration, all auto-allocated
+#
+# Instance name rules:
+# - 1-64 alphanumeric/underscore/hyphen characters
+# - Cannot start with dot
+# - Reserved names: default, config, tmp
+#
+# Port auto-allocation: base + index * 1000
+# - index 0: default instance (18092/19000/19001/5173)
+# - index 1+: named instances
+
+instances: {}
+"""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(template, encoding='utf-8')
+ logger.info("Created instances.yaml template: %s", path)
+ return path
+
+
+def update_instances_yaml(
+ name: str, workspace: Path, ports: dict | None = None
+) -> None:
+ """Add or update instance entry in instances.yaml with full configuration.
+
+ Args:
+ name: Instance name
+ workspace: Workspace path
+ ports: Optional ports dict (if None, will be auto-allocated)
+ """
+ # Import locally to avoid circular dependency
+ from jiuwenclaw.instance_manager.config import calculate_instance_ports
+
+ data = load_instances_yaml()
+ if "instances" not in data:
+ data["instances"] = {}
+
+ # Calculate ports if not provided
+ if ports is None:
+ # Get index for port calculation
+ existing_names = list(data.get("instances", {}).keys())
+ if name in existing_names:
+ index = existing_names.index(name) + 1
+ else:
+ index = len(existing_names) + 1
+ ports = calculate_instance_ports(index)
+
+ # Write full configuration to YAML
+ data["instances"][name] = {
+ "workspace": str(workspace),
+ "ports": ports,
+ }
+ save_instances_yaml(data)
+
+
+def get_instance_index(name: str) -> int:
+ """Get instance declaration order index (starts from 1, 0 reserved for default)."""
+ data = load_instances_yaml()
+ instances = list(data.get("instances", {}).keys())
+ try:
+ return instances.index(name) + 1
+ except ValueError:
+ # New instance not yet in yaml, will be appended
+ return len(instances) + 1
\ No newline at end of file
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py
index 7514c3bad9..8716c45dba 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py
@@ -23,6 +23,13 @@ from datetime import datetime
from pathlib import Path
from typing import Any
+# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径
+try:
+ from jiuwenclaw.utils import get_agent_root_dir
+ _has_jiuwenclaw = True
+except ImportError:
+ _has_jiuwenclaw = False
+
# 修复 Windows 控制台编码问题
if sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
@@ -30,17 +37,37 @@ if sys.platform == "win32":
def get_workspace_dir() -> Path:
- """获取 Agent 根目录(含 memory/、sessions/、skills/)。"""
+ """获取 Agent 根目录(含 memory/、sessions/、skills/)。
+
+ 优先级:
+ 1. jiuwenclaw.utils.get_agent_root_dir()(如果可用)
+ 2. JIUWENCLAW_DATA_DIR 环境变量 / agent
+ 3. JIUWENCLAW_AGENT_ROOT 环境变量
+ 4. 默认 ~/.jiuwenclaw/agent
+ """
+ if _has_jiuwenclaw:
+ return get_agent_root_dir()
+
+ # 检查多实例环境变量
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ return Path(env_workspace) / "agent"
+
+ # 检查旧的 AGENT_ROOT 环境变量
if "JIUWENCLAW_AGENT_ROOT" in os.environ:
return Path(os.environ["JIUWENCLAW_AGENT_ROOT"])
+
+ # 默认路径
home_agent = Path.home() / ".jiuwenclaw" / "agent"
if home_agent.is_dir():
return home_agent
- # 开发:包内 resources/agent
+
+ # 开发模式:包内 resources/agent
script_dir = Path(__file__).resolve()
pkg_agent = script_dir.parent.parent.parent # daily-report -> skills -> agent
if (pkg_agent / "memory").is_dir() or (pkg_agent / "skills").is_dir():
return pkg_agent
+
return home_agent
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py
index 1b065934ba..25ee298670 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py
@@ -19,11 +19,25 @@ from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
-# 加载 ~/.jiuwenclaw/config/.env
+# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径
+try:
+ from jiuwenclaw.utils import get_agent_root_dir, get_env_file
+ _has_jiuwenclaw = True
+except ImportError:
+ _has_jiuwenclaw = False
+
+# 加载配置环境变量
try:
from dotenv import load_dotenv
- _cfg_env = Path.home() / ".jiuwenclaw" / "config" / ".env"
+ if _has_jiuwenclaw:
+ _cfg_env = get_env_file()
+ else:
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ _cfg_env = Path(env_workspace) / "config" / ".env"
+ else:
+ _cfg_env = Path.home() / ".jiuwenclaw" / "config" / ".env"
if _cfg_env.exists():
load_dotenv(_cfg_env)
except ImportError:
@@ -53,10 +67,26 @@ except ImportError:
SKILL_DIR = Path(__file__).parent
PACKAGE_ROOT = SKILL_DIR.parent.parent.parent.parent
REPO_ROOT = PACKAGE_ROOT.parent
-AGENT_ROOT = Path(
- os.environ.get("JIUWENCLAW_AGENT_ROOT", str(Path.home() / ".jiuwenclaw" / "agent"))
-)
-CONFIG_ENV = Path.home() / ".jiuwenclaw" / "config" / ".env"
+
+# Agent 根目录:优先使用 jiuwenclaw.utils,其次环境变量,最后硬编码
+if _has_jiuwenclaw:
+ AGENT_ROOT = get_agent_root_dir()
+else:
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ AGENT_ROOT = Path(env_workspace) / "agent"
+ else:
+ AGENT_ROOT = Path(os.environ.get("JIUWENCLAW_AGENT_ROOT", str(Path.home() / ".jiuwenclaw" / "agent")))
+
+# 配置环境文件路径
+if _has_jiuwenclaw:
+ CONFIG_ENV = get_env_file()
+else:
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ CONFIG_ENV = Path(env_workspace) / "config" / ".env"
+ else:
+ CONFIG_ENV = Path.home() / ".jiuwenclaw" / "config" / ".env"
# 报告用「日历日/当前年月」与项目 cron 默认时区一致(避免 naive datetime)
_REPORT_TZ = ZoneInfo("Asia/Shanghai")
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py
index 323b886984..a00d0a42a5 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py
@@ -4,6 +4,7 @@ import argparse
import json
import locale
import logging
+import os
import re
import sys
import warnings
@@ -12,6 +13,13 @@ from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
+# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径
+try:
+ from jiuwenclaw.utils import get_agent_sessions_dir
+ _has_jiuwenclaw = True
+except ImportError:
+ _has_jiuwenclaw = False
+
try:
from zoneinfo import ZoneInfo
except ImportError: # pragma: no cover
@@ -72,8 +80,13 @@ class Hit:
def _default_sessions_root() -> Path:
- home = Path.home()
- return home / ".jiuwenclaw" / "agent" / "sessions"
+ if _has_jiuwenclaw:
+ return get_agent_sessions_dir()
+ # Fallback: check environment variable or use hardcoded path
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ return Path(env_workspace) / "agent" / "sessions"
+ return Path.home() / ".jiuwenclaw" / "agent" / "sessions"
def _to_float_ts(v: Any, tz: timezone) -> float | None:
diff --git a/jiuwenclaw/scripts/watch-folders.js b/jiuwenclaw/scripts/watch-folders.js
index fbb0f69889..aa4c5a9980 100644
--- a/jiuwenclaw/scripts/watch-folders.js
+++ b/jiuwenclaw/scripts/watch-folders.js
@@ -20,8 +20,18 @@ generate();
// 监听 agent 目录的变化
const chokidar = require('chokidar');
+
+// 优先使用环境变量,支持多实例
+const envWorkspace = process.env.JIUWENCLAW_DATA_DIR;
const homeDir = process.env.USERPROFILE || process.env.HOME || '';
-const userAgentDir = homeDir ? path.join(homeDir, '.jiuwenclaw', 'agent') : '';
+
+let userAgentDir = '';
+if (envWorkspace) {
+ userAgentDir = path.join(envWorkspace, 'agent');
+} else if (homeDir) {
+ userAgentDir = path.join(homeDir, '.jiuwenclaw', 'agent');
+}
+
const fallbackRepoAgentDir = path.join(__dirname, '../resources/agent');
const watchTarget = userAgentDir || fallbackRepoAgentDir;
const watcher = chokidar.watch(watchTarget, {
diff --git a/jiuwenclaw/start_services.py b/jiuwenclaw/start_services.py
index 722c99a4e4..103485f038 100644
--- a/jiuwenclaw/start_services.py
+++ b/jiuwenclaw/start_services.py
@@ -1,17 +1,52 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""Launch JiuwenClaw frontend/backend services with one command."""
+"""Launch JiuWenClaw frontend/backend services with one command.
+
+Supports ``--dotenv <path>`` for multi-instance isolation.
+
+Multi-instance management commands:
+- ``--list``: List all instances with their status
+- ``--status <name>``: Show detailed status of an instance
+- ``--stop <name>``: Stop a running instance
+- ``--restart <name>``: Restart an instance
+- ``--name <name>``: Start a named instance with mode
+"""
from __future__ import annotations
import argparse
+import os
import signal
import subprocess
import sys
import time
from pathlib import Path
-from jiuwenclaw.utils import get_root_dir, is_package_installation
+# --- Early --dotenv parsing (before jiuwenclaw imports) ---
+from jiuwenclaw.dotenv_early import parse_dotenv_early
+parse_dotenv_early("jiuwenclaw-start")
+
+# --- Now safe to import jiuwenclaw modules ---
+from jiuwenclaw.utils import get_root_dir, get_user_workspace_dir, is_package_installation
+from jiuwenclaw.instance_manager import (
+ InstanceConfig,
+ InstanceLock,
+ InstanceStatus,
+ calculate_instance_ports,
+ create_bootstrap_env,
+ format_status_line,
+ get_default_instance_status,
+ get_instance_config,
+ get_instance_status,
+ is_port_available,
+ list_all_instances,
+ stop_instance_process,
+ stop_process_by_pid,
+ validate_instance_name,
+ write_pid_file,
+ PORT_TYPES,
+ compute_auto_port,
+)
# Runtime data root:
# - source mode: repository root
@@ -27,17 +62,225 @@ PACKAGE_DIR = Path(__file__).resolve().parent
WEB_DEV_DIR = PACKAGE_DIR / "web"
-def _build_commands(mode: str) -> list[tuple[str, list[str], Path]]:
+# =============================================================================
+# Instance Command Base Class - Unified handling for all instance operations
+# =============================================================================
+
+class InstanceCommand:
+ """Unified base class for instance management commands.
+
+ Handles:
+ - Instance name validation
+ - Config loading (default or named)
+ - Status retrieval
+ - Error message formatting
+
+ Usage:
+ cmd = InstanceCommand(name)
+ error = cmd.validate_and_load()
+ if error:
+ return error # Already printed error message
+ # Now cmd.config, cmd.status are ready
+ """
+
+ def __init__(self, name: str):
+ self.name = name
+ self.is_default = (name == "default")
+ self.config: InstanceConfig | None = None
+ self.status: InstanceStatus | None = None
+
+ def validate_and_load(self) -> int | None:
+ """Validate instance name and load config/status.
+
+ Returns:
+ Error code if validation/loading failed, None if successful.
+ Error message is already printed to stdout.
+ """
+ # Handle default instance specially
+ if self.is_default:
+ self.status = get_default_instance_status()
+ # Build synthetic config for default instance
+ workspace = get_user_workspace_dir()
+ ports = {pt: compute_auto_port(pt, 0) for pt in PORT_TYPES}
+ self.config = InstanceConfig(name="default", workspace=workspace, ports=ports)
+ return None
+
+ # Validate instance name
+ error = validate_instance_name(self.name)
+ if error:
+ print(f"[start_services] ERROR: {error}")
+ return 1
+
+ # Load instance config from instances.yaml
+ self.config = get_instance_config(self.name)
+ if self.config is None:
+ print(f"[start_services] ERROR: Instance '{self.name}' not found in instances.yaml")
+ print(f"[start_services] Run 'jiuwenclaw-init --name {self.name}' to create it.")
+ return 1
+
+ # Get current status
+ self.status = get_instance_status(self.config)
+ return None
+
+ def check_workspace_exists(self) -> int | None:
+ """Check if workspace directory exists.
+
+ Returns:
+ Error code if workspace missing, None if exists.
+ """
+ if self.config is None:
+ return 1
+ if not self.config.workspace.exists():
+ print(f"[start_services] ERROR: Workspace directory not found: {self.config.workspace}")
+ print(f"[start_services] Run 'jiuwenclaw-init --name {self.name}' to create it.")
+ return 1
+ return None
+
+ def check_running(self) -> bool | None:
+ """Check if instance is running.
+
+ Returns:
+ True if running, False if not running, None if status unavailable.
+ """
+ if self.status is None:
+ return None
+ return self.status.running
+
+ def check_ports_available(self) -> int | None:
+ """Check if all instance ports are available (for start operation).
+
+ Returns:
+ Error code if port conflicts, None if all ports available.
+ """
+ if self.config is None:
+ return 1
+
+ print(f"[start_services] Checking ports for instance '{self.name}'...")
+ conflicts = []
+
+ for port_type, port in self.config.ports.items():
+ if not is_port_available("127.0.0.1", port):
+ conflicts.append((port_type, port))
+ print(f" ✗ {port_type}: {port} - already in use")
+ else:
+ print(f" ✓ {port_type}: {port} - available")
+
+ if conflicts:
+ print("[start_services] ERROR: Port conflicts detected, cannot start instance.")
+ return 1
+
+ return None
+
+
+def print_instance_details(status: InstanceStatus) -> None:
+ """Print detailed instance status in unified format.
+
+ Args:
+ status: InstanceStatus to display
+ """
+ print(f"Instance: {status.name}")
+ print(f"Status: {'running' if status.running else 'stopped'}")
+ print(f"PID: {status.pid or '-'}")
+ print(f"Workspace: {status.workspace}")
+ print("Ports:")
+ for port_type in PORT_TYPES:
+ port = status.ports.get(port_type, 0)
+ print(f" {port_type}: {port}")
+
+ if status.started_at:
+ from datetime import datetime
+ started_dt = datetime.fromtimestamp(status.started_at)
+ print(f"Started at: {started_dt.isoformat()}")
+
+
+def do_stop_instance(cmd: InstanceCommand) -> int:
+ """Execute stop operation for an instance.
+
+ Args:
+ cmd: InstanceCommand with validated config/status
+
+ Returns:
+ Exit code
+ """
+ if cmd.status is None or cmd.config is None:
+ return 1
+
+ pid = cmd.status.pid
+ print(f"[start_services] Stopping instance '{cmd.name}' (PID={pid})...")
+
+ if cmd.is_default:
+ success = stop_process_by_pid(pid, timeout=10.0)
+ else:
+ success = stop_instance_process(cmd.config, timeout=10.0)
+
+ if success:
+ print(f"[start_services] Instance '{cmd.name}' stopped.")
+ return 0
+ else:
+ print(f"[start_services] Failed to stop instance '{cmd.name}'.")
+ return 1
+
+
+def _run_instance_with_pid(commands: list[tuple[str, list[str], Path]],
+ config: InstanceConfig) -> int:
+ """Run processes for an instance with PID file management.
+
+ Args:
+ commands: List of (name, command, cwd) tuples
+ config: InstanceConfig for PID file writing
+
+ Returns:
+ Exit code
+ """
+ processes: dict[str, subprocess.Popen[bytes]] = {}
+ try:
+ for cmd_name, cmd_args, cwd in commands:
+ processes[cmd_name] = _start_process(cmd_name, cmd_args, cwd)
+
+ write_pid_file(config, os.getpid(), time.time())
+ print(f"[start_services] Instance '{config.name}' started")
+
+ _wait_for_services_ready(config.ports, processes)
+
+ while True:
+ for cmd_name, proc in processes.items():
+ code = proc.poll()
+ if code is not None:
+ print(f"[start_services] {cmd_name} exited with code {code}")
+ return code
+ time.sleep(0.5)
+
+ except KeyboardInterrupt:
+ print("\n[start_services] Keyboard interrupt received, shutting down...")
+ return 130
+ finally:
+ _terminate_processes(processes)
+
+
+def _build_commands(mode: str, dotenv_path: Path | None = None) -> list[tuple[str, list[str], Path]]:
+ """Build startup commands for instance.
+
+ Args:
+ mode: Start mode (all/app/web/dev)
+ dotenv_path: Optional path to bootstrap .env for named instance
+
+ Returns:
+ List of (name, command, cwd) tuples
+ """
python_cmd = sys.executable
commands: list[tuple[str, list[str], Path]] = []
- # Always launch package modules so source/package layouts behave the same.
+ # Build --dotenv argument if provided
+ dotenv_arg = ["--dotenv", str(dotenv_path)] if dotenv_path else []
+
if mode in ("all", "app", "dev"):
- commands.append(("app", [python_cmd, "-m", "jiuwenclaw.app"], DATA_ROOT))
- if mode == "all":
- commands.append(("web", [python_cmd, "-m", "jiuwenclaw.app_web"], DATA_ROOT))
- elif mode == "web":
- commands.append(("web", [python_cmd, "-m", "jiuwenclaw.app_web"], DATA_ROOT))
+ cmd = [python_cmd, "-m", "jiuwenclaw.app"] + dotenv_arg
+ commands.append(("app", cmd, DATA_ROOT))
+
+ if mode in ("all", "web"):
+ cmd = [python_cmd, "-m", "jiuwenclaw.app_web"] + dotenv_arg
+ commands.append(("web", cmd, DATA_ROOT))
+
elif mode == "dev":
package_json = WEB_DEV_DIR / "package.json"
if is_package_installation() and not package_json.exists():
@@ -45,21 +288,23 @@ def _build_commands(mode: str) -> list[tuple[str, list[str], Path]]:
"dev mode is unavailable in package installation; "
"please run app/web mode, or use source checkout for frontend dev."
)
- commands.append(("web-dev", ["npm", "run", "dev"], WEB_DEV_DIR))
+ # npm doesn't use --dotenv, ports passed via inherited env vars
+ npm_cmd = ["npm", "run", "dev"]
+ if sys.platform == "win32":
+ npm_cmd = ["cmd", "/c", *npm_cmd]
+ commands.append(("web-dev", npm_cmd, WEB_DEV_DIR))
+
return commands
def _start_process(name: str, cmd: list[str], cwd: Path) -> subprocess.Popen[bytes]:
+ """Start a single subprocess."""
print(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")
- # Windows: npm/npx resolve to .cmd shims; CreateProcess cannot spawn .cmd without a shell.
- if sys.platform == "win32" and cmd:
- first = cmd[0].lower()
- if first in ("npm", "npx"):
- cmd = ["cmd", "/c", *cmd]
return subprocess.Popen(cmd, cwd=str(cwd))
def _terminate_processes(processes: dict[str, subprocess.Popen[bytes]]) -> None:
+ """Terminate all running processes gracefully."""
for name, proc in processes.items():
if proc.poll() is None:
print(f"[start_services] terminating {name} (pid={proc.pid})")
@@ -77,12 +322,53 @@ def _terminate_processes(processes: dict[str, subprocess.Popen[bytes]]) -> None:
proc.kill()
-def _run(mode: str) -> int:
- commands = _build_commands(mode)
- if not commands:
- print(f"[start_services] no commands to run for mode: {mode}")
- return 2
+def _wait_for_services_ready(ports: dict[str, int], processes: dict[str, subprocess.Popen[bytes]]) -> None:
+ """Wait for services to be ready and log startup info."""
+ import socket
+
+ def _check_port(port: int, timeout: float = 3.0) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.settimeout(0.5)
+ sock.connect(("127.0.0.1", port))
+ return True
+ except OSError:
+ time.sleep(0.3)
+ return False
+
+ # Service definitions: (proc_name, port_key, name, url_prefix)
+ services = [
+ ("app", "agent_server", "AgentServer WebSocket", "ws://"),
+ ("app", "gateway", "Gateway HTTP", "http://"),
+ ("app", "web", "WebChannel WebSocket", "ws://"),
+ ("web", "frontend", "Frontend HTTP", "http://"),
+ ]
+
+ for proc_name, port_key, svc_name, url_prefix in services:
+ proc = processes.get(proc_name)
+ if proc is None or proc.poll() is not None:
+ continue
+
+ port = ports.get(port_key, 0)
+ path_suffix = "/ws" if port_key == "web" else ""
+
+ if _check_port(port):
+ print(f"[start_services] ✓ {svc_name} ready at {url_prefix}127.0.0.1:{port}{path_suffix}")
+ else:
+ print(f"[start_services] ⏳ {svc_name} starting... (port {port})")
+
+def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:
+ """Run processes and wait for them.
+
+ Args:
+ commands: List of (name, command, cwd) tuples
+
+ Returns:
+ Exit code
+ """
processes: dict[str, subprocess.Popen[bytes]] = {}
try:
for name, cmd, cwd in commands:
@@ -102,10 +388,173 @@ def _run(mode: str) -> int:
_terminate_processes(processes)
+def _run(mode: str) -> int:
+ """Run default instance (existing behavior)."""
+ commands = _build_commands(mode)
+ if not commands:
+ print(f"[start_services] no commands to run for mode: {mode}")
+ return 2
+ return _run_processes(commands)
+
+
+def _action_list() -> int:
+ """List all instances with their status.
+
+ Returns:
+ Exit code (0 for success)
+ """
+ statuses = list_all_instances(include_default=True)
+
+ if not statuses:
+ print("[start_services] No instances configured.")
+ print("[start_services] Run 'jiuwenclaw-init' to initialize default instance.")
+ return 0
+
+ # Print table header
+ print("INSTANCE STATUS PID WORKSPACE PORTS")
+ print("-" * 80)
+
+ for status in statuses:
+ print(format_status_line(status))
+
+ return 0
+
+
+def _action_status(name: str) -> int:
+ """Show detailed status of a specific instance.
+
+ Args:
+ name: Instance name
+
+ Returns:
+ Exit code
+ """
+ cmd = InstanceCommand(name)
+ error = cmd.validate_and_load()
+ if error is not None:
+ return error
+
+ print_instance_details(cmd.status)
+ return 0
+
+
+def _action_stop(name: str) -> int:
+ """Stop a running instance.
+
+ Args:
+ name: Instance name
+
+ Returns:
+ Exit code
+ """
+ cmd = InstanceCommand(name)
+ error = cmd.validate_and_load()
+ if error is not None:
+ return error
+
+ running = cmd.check_running()
+ if running is None:
+ return 1
+ if not running:
+ print(f"[start_services] Instance '{name}' is not running.")
+ return 0
+
+ # Execute stop
+ return do_stop_instance(cmd)
+
+
+def _action_restart(name: str, mode: str = "all") -> int:
+ """Restart an instance (stop then start).
+
+ Args:
+ name: Instance name
+ mode: Start mode (all/app/web/dev)
+
+ Returns:
+ Exit code
+ """
+ print(f"[start_services] Restarting instance '{name}'...")
+
+ # Validate and load first (common check for both stop and start)
+ cmd = InstanceCommand(name)
+ error = cmd.validate_and_load()
+ if error is not None:
+ return error
+
+ # First stop (only if running)
+ if cmd.check_running():
+ stop_result = do_stop_instance(cmd)
+ if stop_result != 0:
+ print("[start_services] Restart aborted: stop failed.")
+ return stop_result
+ # Wait for process to fully exit
+ time.sleep(1)
+
+ # Then start
+ if cmd.is_default:
+ start_result = _run(mode)
+ else:
+ start_result = _start_named_instance(name, mode)
+
+ if start_result != 0:
+ print("[start_services] Restart failed: start failed.")
+ return start_result
+
+ print(f"[start_services] Instance '{name}' restarted.")
+ return 0
+
+
+def _start_named_instance(name: str, mode: str) -> int:
+ """Start a named instance.
+
+ Args:
+ name: Instance name
+ mode: Start mode (all/app/web/dev)
+
+ Returns:
+ Exit code
+ """
+ cmd = InstanceCommand(name)
+ if cmd.validate_and_load():
+ return 1
+ if cmd.check_workspace_exists():
+ return 1
+ if cmd.check_running():
+ print(f"[start_services] ERROR: Instance '{cmd.name}' is already running (PID={cmd.status.pid})")
+ return 1
+ if cmd.check_ports_available():
+ return 1
+
+ config = cmd.config
+ if config is None:
+ return 1
+
+ # Acquire startup lock to prevent concurrent starts
+ lock = InstanceLock(config)
+ if not lock.acquire(timeout=5.0):
+ print(f"[start_services] ERROR: Instance '{name}' startup in progress by another process")
+ print(f"[start_services] Wait a few seconds or check if another terminal is starting this instance.")
+ return 1
+
+ try:
+ dotenv_path = create_bootstrap_env(config)
+ commands = _build_commands(mode, dotenv_path)
+ if not commands:
+ print(f"[start_services] ERROR: No commands for mode: {mode}")
+ return 2
+
+ return _run_instance_with_pid(commands, config)
+ finally:
+ lock.release()
+
+
def _parse_args() -> argparse.Namespace:
+ """Parse CLI arguments."""
parser = argparse.ArgumentParser(
- description="Launch JiuwenClaw services (frontend/backend).",
+ description="Launch JiuWenClaw services (frontend/backend).",
)
+
+ # Basic start parameter: mode (optional, default all)
parser.add_argument(
"mode",
nargs="?",
@@ -113,15 +562,98 @@ def _parse_args() -> argparse.Namespace:
choices=["all", "web", "app", "dev"],
help="Start mode: all (default), web, app, or dev.",
)
+
+ # Instance specification parameter
+ parser.add_argument(
+ "--name",
+ metavar="<name>",
+ help="Start a named instance from instances.yaml.",
+ )
+
+ # Management function parameters (mutually exclusive group)
+ management_group = parser.add_mutually_exclusive_group()
+ management_group.add_argument(
+ "--list",
+ action="store_true",
+ help="List all instances with their status.",
+ )
+ management_group.add_argument(
+ "--status",
+ metavar="<name>",
+ help="Show status of a specific instance.",
+ )
+ management_group.add_argument(
+ "--stop",
+ metavar="<name>",
+ help="Stop a running instance.",
+ )
+ management_group.add_argument(
+ "--restart",
+ metavar="<name>",
+ help="Restart an instance (stop then start).",
+ )
+
return parser.parse_args()
+def _validate_args(args: argparse.Namespace) -> int | None:
+ """Validate argument combinations, return error code or None if valid."""
+ # Management params are mutually exclusive with mode (handled by argparse)
+ # --name is mutually exclusive with management params (handled by argparse)
+
+ # Additional validation: --restart needs valid mode
+ if args.restart and args.mode not in ("all", "app", "web"):
+ print(f"[start_services] ERROR: Invalid mode '{args.mode}' for --restart")
+ return 1
+
+ return None
+
+
+def _dispatch_action(args: argparse.Namespace) -> int:
+ """Dispatch action based on parsed arguments.
+
+ Args:
+ args: Parsed arguments
+
+ Returns:
+ Exit code
+ """
+ # Validate arguments
+ error_code = _validate_args(args)
+ if error_code is not None:
+ return error_code
+
+ # --list: list all instances
+ if args.list:
+ return _action_list()
+
+ # --status <name>: show specific instance status
+ if args.status:
+ return _action_status(args.status)
+
+ # --stop <name>: stop specific instance
+ if args.stop:
+ return _action_stop(args.stop)
+
+ # --restart <name>: restart specific instance
+ if args.restart:
+ return _action_restart(args.restart, args.mode)
+
+ # --name <name>: start named instance
+ if args.name:
+ return _start_named_instance(args.name, args.mode)
+
+ # Default: start default instance (existing behavior)
+ return _run(args.mode)
+
+
def main() -> None:
+ """CLI entry point."""
signal.signal(signal.SIGTERM, signal.default_int_handler)
args = _parse_args()
- exit_code = _run(args.mode)
+ exit_code = _dispatch_action(args)
raise SystemExit(exit_code)
if __name__ == "__main__":
- main()
+ main()
\ No newline at end of file
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.py
index 31a4221f4d..7361467cbd 100644
--- a/jiuwenclaw/utils.py
+++ b/jiuwenclaw/utils.py
@@ -232,20 +232,26 @@ def _resolve_logging_levels(
return LoggingLevels(logger_level, console, gateway, channel, agent_server, full)
-# 用户数据根(config、agent、.logs 等)。供 config 模块在 import 时读取;仅依赖 os/path,不引用本包其它模块。
-_raw_data_dir = os.environ.get("JIUWENCLAW_DATA_DIR", "").strip()
-JIUWENCLAW_DATA_DIR = (
- Path(_raw_data_dir).expanduser().resolve() if _raw_data_dir else Path.home() / ".jiuwenclaw"
-)
-
_user_home: Path | None = None
+_workspace_base_dir: Path | None = None
def get_user_home() -> Path:
- """Get the current user home directory."""
+ """Get the current user home directory.
+
+ Priority:
+ 1. Cached value (if already set via set_user_home or previous call)
+ 2. JIUWENCLAW_HOME environment variable
+ 3. System default Path.home()
+ """
global _user_home
- if _user_home is None:
- _user_home = Path.home()
+ if _user_home is not None:
+ return _user_home
+ env_home = os.getenv("JIUWENCLAW_HOME")
+ if env_home:
+ _user_home = Path(env_home)
+ return _user_home
+ _user_home = Path.home()
return _user_home
@@ -253,7 +259,7 @@ def set_user_home(path: Path, initialized: bool = False) -> None:
"""Set a custom user home directory.
After calling this function, all path getters will return paths based on the new home directory.
-
+
Args:
path: The new user home directory path.
initialized: If True, skip cache reset (use when paths are already initialized elsewhere).
@@ -269,10 +275,24 @@ def set_user_home(path: Path, initialized: bool = False) -> None:
def get_user_workspace_dir() -> Path:
- """用户数据根目录:若设置 ``JIUWENCLAW_DATA_DIR`` 则为其解析路径,否则为 ``<user home>/.jiuwenclaw``。"""
- if _raw_data_dir:
- return JIUWENCLAW_DATA_DIR
- return get_user_home() / ".jiuwenclaw"
+ """Get the user workspace directory path (~/.jiuwenclaw or custom path).
+
+ Priority:
+ 1. Cached value (if already set via set_user_workspace_dir or previous call)
+ 2. JIUWENCLAW_DATA_DIR environment variable (for multi-instance isolation)
+ 3. get_user_home() / ".jiuwenclaw" (default instance)
+ """
+ global _workspace_base_dir
+ if _workspace_base_dir is not None:
+ return _workspace_base_dir
+ env_workspace = os.getenv("JIUWENCLAW_DATA_DIR")
+ if env_workspace:
+ _workspace_base_dir = Path(env_workspace)
+ return _workspace_base_dir
+ _workspace_base_dir = get_user_home() / ".jiuwenclaw"
+ return _workspace_base_dir
+
+
# Cache for resolved paths
@@ -805,6 +825,21 @@ def prepare_workspace(
set_preferred_language_in_config_file(config_yaml_dest, resolved_lang)
+def _close_log_handlers() -> None:
+ """Close all jiuwenclaw log handlers to release file locks.
+
+ This is needed before deleting workspace directory in init -f mode,
+ because setup_logger() runs at module import time and opens log files.
+ """
+ root = logging.getLogger("jiuwenclaw")
+ for handler in root.handlers[:]:
+ try:
+ handler.close()
+ root.removeHandler(handler)
+ except Exception:
+ pass # Ignore errors during cleanup
+
+
def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
"""Initialize ~/.jiuwenclaw from package or source resources.
@@ -833,8 +868,8 @@ def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
if overwrite:
# Force mode: explain both modes and ask for confirmation
print(
- "[jiuwenclaw-init] With -f/--force flag, "
- "entire ~/.jiuwenclaw will be deleted for clean initialization."
+ f"[jiuwenclaw-init] With -f/--force flag, "
+ f"entire {workspace_dir} will be deleted for clean initialization."
)
print("[jiuwenclaw-init] WARNING: This will delete all historical configuration and memory information.")
print("[jiuwenclaw-init] This action cannot be undone.")
@@ -846,12 +881,14 @@ def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
return "cancelled"
+ # Close all log handlers to release file locks before deleting
+ _close_log_handlers()
+
# Delete entire workspace directory for clean initialization
try:
shutil.rmtree(workspace_dir)
- logger.info(f"Removed workspace directory: {workspace_dir}")
+ print(f"[jiuwenclaw-init] Removed workspace directory: {workspace_dir}")
except OSError as e:
- logger.error(f"Failed to remove workspace directory: {e}")
print(f"[jiuwenclaw-init] ERROR: Failed to remove workspace: {e}")
return "cancelled"
else:
diff --git a/jiuwenclaw/web/vite.config.ts b/jiuwenclaw/web/vite.config.ts
index 47a0247b49..f987514e29 100644
--- a/jiuwenclaw/web/vite.config.ts
+++ b/jiuwenclaw/web/vite.config.ts
@@ -24,6 +24,12 @@ function resolveProjectRootDir(): string {
}
const home = process.env.USERPROFILE || process.env.HOME || ''
if (home) {
+ // 优先检查多实例环境变量
+ const envWorkspace = process.env.JIUWENCLAW_DATA_DIR
+ if (envWorkspace) {
+ console.log('[file-api] 使用 JIUWENCLAW_DATA_DIR:', path.resolve(envWorkspace))
+ return path.resolve(envWorkspace)
+ }
const userWorkspace = path.join(home, '.jiuwenclaw')
if (fs.existsSync(userWorkspace)) {
console.log('[file-api] 使用用户工作区:', path.resolve(userWorkspace))
diff --git a/tests/unit_tests/test_instance_manager.py b/tests/unit_tests/test_instance_manager.py
new file mode 100644
index 0000000000..9f2dc270c0
--- /dev/null
+++ b/tests/unit_tests/test_instance_manager.py
@@ -0,0 +1,837 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for instance_manager module.
+
+Tests for:
+- Instance name validation
+- Port auto-allocation
+- Port conflict detection
+- PID file management
+- Instance status querying
+- InstancesYamlError handling
+- InstanceLock concurrency control
+"""
+
+import json
+import os
+import tempfile
+import time
+from pathlib import Path
+from unittest.mock import patch, MagicMock
+
+import pytest
+
+from jiuwenclaw.instance_manager import (
+ InstanceConfig,
+ InstanceLock,
+ InstanceStatus,
+ InstancesYamlError,
+ validate_instance_name,
+ is_valid_instance_name,
+ get_instances_yaml_path,
+ compute_auto_port,
+ calculate_instance_ports,
+ check_port_conflicts,
+ collect_all_ports,
+ write_pid_file,
+ read_pid_file,
+ delete_pid_file,
+ is_process_alive,
+ get_instance_status,
+ get_default_instance_status,
+ list_all_instances,
+ format_status_line,
+ get_instance_config,
+ load_all_instance_configs,
+ create_bootstrap_env,
+ create_bootstrap_env_for_name,
+ stop_instance_process,
+ create_instances_yaml_template,
+ load_instances_yaml,
+ save_instances_yaml,
+ update_instances_yaml,
+ get_instance_index,
+ RESERVED_NAMES,
+ PORT_TYPES,
+ BASE_PORTS,
+ STALE_LOCK_TIMEOUT,
+)
+
+
+# Module-level helper function for multiprocessing (must be at module level to be pickleable)
+def _try_acquire_lock_for_multiprocess(workspace_str: str) -> bool:
+ """Helper function to try acquiring lock in a subprocess.
+
+ This must be at module level to be pickleable for multiprocessing.
+ """
+ from jiuwenclaw.instance_manager import (
+ InstanceConfig as _InstanceConfig,
+ InstanceLock as _InstanceLock,
+ )
+
+ _config = _InstanceConfig(name="test", workspace=Path(workspace_str), ports={})
+ _lock = _InstanceLock(_config)
+ result = _lock.acquire(timeout=0.5) # Short timeout
+ if result:
+ _lock.release()
+ return result
+
+
+def _try_acquire_lock_with_result(workspace_str: str, result_queue) -> None:
+ """Helper function for multiprocessing that returns result via Queue.
+
+ This must be at module level to be pickleable for multiprocessing on Windows.
+ """
+ result = _try_acquire_lock_for_multiprocess(workspace_str)
+ result_queue.put(result)
+
+
+class TestInstanceNameValidation:
+ """Test instance name validation."""
+
+ @staticmethod
+ def test_valid_simple_names():
+ """Test valid simple names."""
+ assert validate_instance_name("alice") is None
+ assert validate_instance_name("bob") is None
+ assert validate_instance_name("my-instance") is None
+ assert validate_instance_name("test_123") is None
+ assert validate_instance_name("a") is None
+
+ @staticmethod
+ def test_valid_complex_names():
+ """Test valid complex names."""
+ assert validate_instance_name("production-server-01") is None
+ assert validate_instance_name("dev_test_env") is None
+ assert validate_instance_name("CamelCaseName") is None
+
+ @staticmethod
+ def test_invalid_empty_name():
+ """Test empty name is invalid."""
+ assert validate_instance_name("") is not None
+ assert validate_instance_name(None) is not None
+
+ @staticmethod
+ def test_invalid_too_long():
+ """Test name longer than 64 chars is invalid."""
+ long_name = "a" * 65
+ assert validate_instance_name(long_name) is not None
+
+ @staticmethod
+ def test_invalid_special_chars():
+ """Test names with special characters are invalid."""
+ assert validate_instance_name("alice@example") is not None
+ assert validate_instance_name("my instance") is not None # space
+ assert validate_instance_name("instance.name") is not None # dot
+ assert validate_instance_name("中文实例") is not None # non-ASCII
+
+ @staticmethod
+ def test_invalid_leading_dot():
+ """Test names starting with dot are invalid."""
+ assert validate_instance_name(".hidden") is not None
+ assert validate_instance_name(".alice") is not None
+
+ @staticmethod
+ def test_reserved_names():
+ """Test reserved names are invalid."""
+ for name in RESERVED_NAMES:
+ assert validate_instance_name(name) is not None
+ assert validate_instance_name(name.upper()) is not None # case insensitive
+
+ @staticmethod
+ def test_is_valid_instance_name():
+ """Test is_valid_instance_name helper."""
+ assert is_valid_instance_name("alice") is True
+ assert is_valid_instance_name("default") is False
+ assert is_valid_instance_name("") is False
+
+
+class TestPortAllocation:
+ """Test port auto-allocation."""
+
+ @staticmethod
+ def test_base_ports():
+ """Test base ports for default instance (index 0)."""
+ assert compute_auto_port("agent_server", 0) == 18092
+ assert compute_auto_port("web", 0) == 19000
+ assert compute_auto_port("gateway", 0) == 19001
+ assert compute_auto_port("frontend", 0) == 5173
+
+ @staticmethod
+ def test_calculate_instance_ports():
+ """Test calculate_instance_ports returns all port types."""
+ ports = calculate_instance_ports(1)
+ assert "agent_server" in ports
+ assert "web" in ports
+ assert "gateway" in ports
+ assert "frontend" in ports
+ assert ports["agent_server"] == 19092
+
+ @staticmethod
+ def test_unknown_port_type():
+ """Test unknown port type uses default base."""
+ assert compute_auto_port("unknown", 0) == 10000
+
+
+class TestPortAvailability:
+ """Test port availability checking."""
+
+ @staticmethod
+ def test_check_port_conflicts_no_conflicts():
+ """Test no conflicts when ports are available."""
+ ports = {"agent_server": 19092, "web": 20000}
+ # Should have no conflicts if ports are free (unlikely to be used)
+ conflicts = check_port_conflicts(ports, "127.0.0.1", [])
+ # This test may fail if ports happen to be occupied
+ # We're testing the logic, not the actual availability
+ assert isinstance(conflicts, list)
+
+ @staticmethod
+ def test_check_port_conflicts_with_existing():
+ """Test conflicts detected when port in existing set."""
+ ports = {"agent_server": 19092}
+ existing = [19092]
+ conflicts = check_port_conflicts(ports, "127.0.0.1", existing)
+ assert 19092 in conflicts
+
+
+class TestInstanceConfig:
+ """Test InstanceConfig dataclass."""
+
+ @staticmethod
+ def test_basic_config():
+ """Test basic InstanceConfig creation."""
+ config = InstanceConfig(
+ name="alice",
+ workspace=Path("/tmp/alice"),
+ ports={"agent_server": 19092, "web": 20000},
+ )
+ assert config.name == "alice"
+ assert "alice" in str(config.workspace)
+ assert config.ports["agent_server"] == 19092
+
+
+class TestPidFileManagement:
+ """Test PID file management."""
+
+ @staticmethod
+ def test_write_and_read_pid_file(tmp_path):
+ """Test writing and reading PID file."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ pid = 12345
+ write_pid_file(config, pid)
+
+ data = read_pid_file(config)
+ assert data is not None
+ assert data["pid"] == pid
+ assert data["name"] == "test"
+ assert "started_at" in data
+
+ @staticmethod
+ def test_read_nonexistent_pid_file(tmp_path):
+ """Test reading nonexistent PID file."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ data = read_pid_file(config)
+ assert data is None
+
+ @staticmethod
+ def test_delete_pid_file(tmp_path):
+ """Test deleting PID file."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ write_pid_file(config, 12345)
+ assert config.get_pid_file_path().exists()
+
+ deleted = delete_pid_file(config)
+ assert deleted is True
+ assert not config.get_pid_file_path().exists()
+
+ # Second delete returns False
+ deleted2 = delete_pid_file(config)
+ assert deleted2 is False
+
+
+class TestInstanceStatus:
+ """Test InstanceStatus and status querying."""
+
+ @staticmethod
+ def test_get_instance_status_stopped(tmp_path):
+ """Test getting status for stopped instance."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={"agent_server": 19092},
+ )
+ status = get_instance_status(config)
+ assert status.name == "test"
+ assert status.running is False
+ assert status.pid is None
+
+ @staticmethod
+ def test_get_instance_status_running_with_dead_pid(tmp_path):
+ """Test status returns stopped when PID file exists but process is dead."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ # Write PID file with unlikely PID
+ write_pid_file(config, 999999999)
+
+ status = get_instance_status(config)
+ assert status.running is False
+ assert status.pid is None
+
+ @staticmethod
+ def test_format_status_line():
+ """Test formatting status line."""
+ status = InstanceStatus(
+ name="alice",
+ running=True,
+ pid=12345,
+ workspace=Path("/tmp/alice"),
+ ports={"agent_server": 19092, "web": 20000},
+ )
+ line = format_status_line(status)
+ assert "alice" in line
+ assert "running" in line
+ assert "12345" in line
+
+ @staticmethod
+ def test_format_status_line_default():
+ """Test formatting default instance status."""
+ status = InstanceStatus(
+ name="default",
+ running=False,
+ pid=None,
+ workspace=Path("/tmp/default"),
+ ports={},
+ )
+ line = format_status_line(status)
+ assert "default" in line
+ assert "stopped" in line
+
+
+class TestIsProcessAlive:
+ """Test process alive checking."""
+
+ @staticmethod
+ def test_invalid_pid():
+ """Test invalid PID returns False."""
+ assert is_process_alive(-1) is False
+ assert is_process_alive(0) is False
+
+ @staticmethod
+ def test_current_process():
+ """Test current process PID is alive."""
+ current_pid = os.getpid()
+ assert is_process_alive(current_pid) is True
+
+
+class TestBootstrapEnv:
+ """Test bootstrap .env creation."""
+
+ @staticmethod
+ def test_create_bootstrap_env(tmp_path):
+ """Test creating bootstrap env file."""
+ config = InstanceConfig(
+ name="alice",
+ workspace=tmp_path,
+ ports={
+ "agent_server": 19092,
+ "web": 20000,
+ "gateway": 20001,
+ "frontend": 6173,
+ },
+ )
+ env_path = create_bootstrap_env(config)
+
+ assert env_path.exists()
+ content = env_path.read_text()
+ assert "JIUWENCLAW_DATA_DIR" in content
+ assert "JIUWENCLAW_INSTANCE=alice" in content
+ assert "AGENT_SERVER_PORT=19092" in content
+
+
+class TestInstancesYaml:
+ """Test instances.yaml management."""
+
+ @staticmethod
+ def test_create_instances_yaml_template(tmp_path):
+ """Test creating instances.yaml template."""
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=tmp_path / "instances.yaml",
+ ):
+ path = create_instances_yaml_template()
+ assert path.exists()
+ content = path.read_text()
+ assert "instances:" in content
+
+ @staticmethod
+ def test_load_empty_instances_yaml(tmp_path):
+ """Test loading nonexistent instances.yaml."""
+ yaml_path = tmp_path / "instances.yaml"
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ data = load_instances_yaml()
+ assert data == {"instances": {}}
+
+ @staticmethod
+ def test_save_and_load_instances_yaml(tmp_path):
+ """Test saving and loading instances.yaml."""
+ yaml_path = tmp_path / "instances.yaml"
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ data = {
+ "instances": {"alice": {}, "bob": {"ports": {"agent_server": 28092}}}
+ }
+ save_instances_yaml(data)
+
+ loaded = load_instances_yaml()
+ assert "alice" in loaded["instances"]
+ assert "bob" in loaded["instances"]
+ assert loaded["instances"]["bob"]["ports"]["agent_server"] == 28092
+
+
+class TestGetInstanceConfig:
+ """Test instance config loading."""
+
+ @staticmethod
+ def test_get_instance_config_not_found(tmp_path):
+ """Test getting nonexistent instance config."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text("instances: {}\n", encoding="utf-8")
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ config = get_instance_config("nonexistent")
+ assert config is None
+
+ @staticmethod
+ def test_get_instance_config_with_auto_ports(tmp_path):
+ """Test getting instance config with auto-allocated ports."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text("instances:\n alice: {}\n", encoding="utf-8")
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ config = get_instance_config("alice")
+ assert config is not None
+ assert config.name == "alice"
+ # First instance (index 1) should have these ports
+ assert config.ports["agent_server"] == 19092
+
+
+class TestCollectAllPorts:
+ """Test collecting all ports for conflict detection."""
+
+ @staticmethod
+ def test_collect_default_ports():
+ """Test collecting default instance ports."""
+ yaml_path = Path("/nonexistent")
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ ports = collect_all_ports()
+ # Default instance ports should be included
+ assert 18092 in ports # agent_server
+ assert 19000 in ports # web
+
+ @staticmethod
+ def test_collect_excluding_self():
+ """Test collecting ports excluding a specific instance."""
+ yaml_path = Path("/nonexistent")
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ ports = collect_all_ports(exclude_name="default")
+ # Should be empty when excluding default and no named instances
+ assert ports == []
+
+
+class TestListAllInstances:
+ """Test listing all instances."""
+
+ @staticmethod
+ def test_list_all_instances_empty(tmp_path):
+ """Test listing with no instances.yaml."""
+ yaml_path = tmp_path / "instances.yaml"
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ statuses = list_all_instances(include_default=True)
+ # Should include default instance
+ assert len(statuses) >= 1
+ assert any(s.name == "default" for s in statuses)
+
+ @staticmethod
+ def test_list_all_instances_no_default(tmp_path):
+ """Test listing without default instance."""
+ yaml_path = tmp_path / "instances.yaml"
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ statuses = list_all_instances(include_default=False)
+ # Should not include default instance
+ assert not any(s.name == "default" for s in statuses)
+
+
+class TestInstancesYamlError:
+ """Test instances.yaml error handling."""
+
+ @staticmethod
+ def test_valid_yaml(tmp_path):
+ """Test loading valid YAML file."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n ports:\n agent_server: 28092\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ data = load_instances_yaml()
+ assert "alice" in data["instances"]
+ assert data["instances"]["alice"]["ports"]["agent_server"] == 28092
+
+ @staticmethod
+ def test_missing_file(tmp_path):
+ """Test missing file returns empty structure."""
+ yaml_path = tmp_path / "nonexistent.yaml"
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ data = load_instances_yaml()
+ assert data == {"instances": {}}
+
+ @staticmethod
+ def test_invalid_yaml_syntax(tmp_path):
+ """Test invalid YAML syntax raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ # Invalid YAML: missing space after colon, duplicate key
+ yaml_path.write_text(
+ "instances:\n alice:bad_syntax\n alice: duplicate\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ # Check error message contains useful info
+ assert "YAML format error" in str(exc_info.value)
+ assert str(yaml_path) in str(exc_info.value)
+
+ @staticmethod
+ def test_missing_instances_key(tmp_path):
+ """Test missing 'instances' key raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text("other_key: value\n", encoding="utf-8")
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "Missing 'instances' key" in str(exc_info.value)
+
+ @staticmethod
+ def test_invalid_instance_name(tmp_path):
+ """Test invalid instance name raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n '.hidden': {}\n", # Invalid: starts with dot
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "Invalid instance name" in str(exc_info.value)
+ assert ".hidden" in str(exc_info.value)
+
+ @staticmethod
+ def test_reserved_instance_name(tmp_path):
+ """Test reserved instance name raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n default: {}\n", # Reserved name
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "reserved" in str(exc_info.value).lower()
+
+ @staticmethod
+ def test_invalid_port_type(tmp_path):
+ """Test unknown port type raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n ports:\n unknown_port: 12345\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "unknown port type" in str(exc_info.value)
+ assert "unknown_port" in str(exc_info.value)
+
+ @staticmethod
+ def test_invalid_port_value_negative(tmp_path):
+ """Test negative port value raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n ports:\n agent_server: -1\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "must be 1-65535" in str(exc_info.value)
+
+ @staticmethod
+ def test_invalid_port_value_out_of_range(tmp_path):
+ """Test port value out of range raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n ports:\n agent_server: 70000\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "must be 1-65535" in str(exc_info.value)
+
+ @staticmethod
+ def test_invalid_port_value_string(tmp_path):
+ """Test string port value raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n"
+ " alice:\n"
+ " ports:\n"
+ ' agent_server: "28092"\n', # String, not int
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "must be integer" in str(exc_info.value)
+
+ @staticmethod
+ def test_ports_not_dict(tmp_path):
+ """Test non-dict ports value raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n ports: invalid\n",
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "'ports' must be a dict" in str(exc_info.value)
+
+ @staticmethod
+ def test_workspace_not_string(tmp_path):
+ """Test non-string workspace raises InstancesYamlError."""
+ yaml_path = tmp_path / "instances.yaml"
+ yaml_path.write_text(
+ "instances:\n alice:\n workspace: 123\n", # Int, not string
+ encoding="utf-8",
+ )
+ with patch(
+ "jiuwenclaw.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ with pytest.raises(InstancesYamlError) as exc_info:
+ load_instances_yaml()
+ assert "'workspace' must be a string" in str(exc_info.value)
+
+
+class TestInstanceLock:
+ """Test InstanceLock concurrency control."""
+
+ @staticmethod
+ def test_acquire_and_release(tmp_path):
+ """Test basic lock acquire and release."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ lock = InstanceLock(config)
+
+ # Should acquire successfully
+ assert lock.acquire(timeout=1.0) is True
+ assert lock.lock_path.exists()
+
+ # Should be able to release
+ lock.release()
+ # On Windows, lock file is removed; on Unix, it may remain
+ assert getattr(lock, "_lock_file") is None
+
+ @staticmethod
+ def test_context_manager(tmp_path):
+ """Test lock as context manager."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+
+ with InstanceLock(config) as lock:
+ assert lock.lock_path.exists()
+ assert getattr(lock, "_lock_file") is not None
+
+ # Released after context
+ assert getattr(lock, "_lock_file") is None
+
+ @staticmethod
+ def test_double_acquire_same_process(tmp_path):
+ """Test that same process can re-acquire after release."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ lock = InstanceLock(config)
+
+ assert lock.acquire(timeout=1.0) is True
+ lock.release()
+
+ # Should be able to acquire again
+ assert lock.acquire(timeout=1.0) is True
+ lock.release()
+
+ @staticmethod
+ def test_concurrent_acquire_fails(tmp_path):
+ """Test that concurrent acquire from another process fails.
+
+ This is the primary test for cross-process lock isolation.
+ test_timeout_exceeded only tests same-process lock object competition,
+ which is a different scenario and cannot replace this test.
+ """
+ import multiprocessing
+
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+ lock = InstanceLock(config)
+
+ # Acquire in this process
+ assert lock.acquire(timeout=1.0) is True
+
+ # Use Queue to get return value from subprocess
+ ctx = multiprocessing.get_context("spawn")
+ result_queue = ctx.Queue()
+
+ p = ctx.Process(
+ target=_try_acquire_lock_with_result, args=(str(tmp_path), result_queue)
+ )
+ p.start()
+ p.join(timeout=5.0)
+
+ # Process should not hang
+ assert not p.is_alive()
+
+ # The other process should fail to acquire lock (return False)
+ # On Windows, the lock file already exists so exclusive creation fails
+ # On Unix, flock on same file from different process fails
+ if not result_queue.empty():
+ subprocess_result = result_queue.get(timeout=1.0)
+ assert subprocess_result is False, (
+ "Subprocess should fail to acquire lock held by main process"
+ )
+
+ lock.release()
+
+ @staticmethod
+ def test_stale_lock_cleanup(tmp_path):
+ """Test that stale lock is cleaned up."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+
+ # Create a stale lock file manually
+ lock_path = tmp_path / ".instance.lock"
+ lock_path.write_text("99999\n0.0\n", encoding="utf-8") # Old timestamp
+
+ # Modify mtime to be old
+ old_time = time.time() - STALE_LOCK_TIMEOUT - 10
+ os.utime(lock_path, (old_time, old_time))
+
+ # Acquire should succeed after cleaning stale lock
+ lock = InstanceLock(config)
+ assert lock.acquire(timeout=1.0) is True
+ lock.release()
+
+ @staticmethod
+ def test_timeout_exceeded(tmp_path):
+ """Test that acquire returns False after timeout."""
+ config = InstanceConfig(
+ name="test",
+ workspace=tmp_path,
+ ports={},
+ )
+
+ # First lock acquires successfully
+ first_lock = InstanceLock(config)
+ assert first_lock.acquire(timeout=1.0) is True
+
+ # Second lock should fail to acquire (timeout exceeded)
+ second_lock = InstanceLock(config)
+ result = second_lock.acquire(timeout=0.5)
+ assert result is False
+
+ # Clean up
+ first_lock.release()
diff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.py
index d36ca8bd3f..324eb6d0a7 100644
--- a/tests/unit_tests/test_utils.py
+++ b/tests/unit_tests/test_utils.py
@@ -131,3 +131,193 @@ class TestConstants:
assert hasattr(utils, "get_user_workspace_dir")
assert isinstance(utils.get_user_workspace_dir(), Path)
assert ".jiuwenclaw" in str(utils.get_user_workspace_dir())
+
+
+class TestMultiInstanceEnvVars:
+ """Test environment variable support for multi-instance isolation (Phase 1)."""
+
+ @staticmethod
+ def test_jiuwenclaw_workspace_env_var():
+ """Test JIUWENCLAW_DATA_DIR environment variable overrides default workspace."""
+ # Reset cache before test - must reset _workspace_base_dir for workspace tests
+ setattr(utils, '_workspace_base_dir', None)
+ setattr(utils, '_user_home', None)
+ original_env = os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+ original_home_env = os.environ.pop("JIUWENCLAW_HOME", None)
+
+ try:
+ # Test default behavior
+ default_workspace = utils.get_user_workspace_dir()
+ assert ".jiuwenclaw" in str(default_workspace)
+
+ # Reset cache and set env var
+ setattr(utils, '_workspace_base_dir', None)
+ setattr(utils, '_user_home', None)
+ os.environ["JIUWENCLAW_DATA_DIR"] = "/custom/workspace/path"
+ custom_workspace = utils.get_user_workspace_dir()
+ # Use Path comparison for cross-platform compatibility
+ assert custom_workspace == Path("/custom/workspace/path")
+ finally:
+ # Cleanup
+ setattr(utils, '_workspace_base_dir', None)
+ setattr(utils, '_user_home', None)
+ os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+ if original_env:
+ os.environ["JIUWENCLAW_DATA_DIR"] = original_env
+ if original_home_env:
+ os.environ["JIUWENCLAW_HOME"] = original_home_env
+
+ @staticmethod
+ def test_jiuwenclaw_home_env_var():
+ """Test JIUWENCLAW_HOME environment variable overrides default home."""
+ # Reset cache before test
+ setattr(utils, '_user_home', None)
+ original_home_env = os.environ.pop("JIUWENCLAW_HOME", None)
+ original_workspace_env = os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+
+ try:
+ # Set JIUWENCLAW_HOME
+ os.environ["JIUWENCLAW_HOME"] = "/custom/home"
+ custom_home = utils.get_user_home()
+ assert custom_home == Path("/custom/home")
+
+ # Workspace should derive from custom home
+ setattr(utils, '_user_home', None)
+ os.environ.pop("JIUWENCLAW_HOME", None) # Clear for fresh test
+ workspace = utils.get_user_workspace_dir()
+ # Without env vars, should use Path.home()
+ assert isinstance(workspace, Path)
+ finally:
+ # Cleanup
+ setattr(utils, '_user_home', None)
+ os.environ.pop("JIUWENCLAW_HOME", None)
+ os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+ if original_home_env:
+ os.environ["JIUWENCLAW_HOME"] = original_home_env
+ if original_workspace_env:
+ os.environ["JIUWENCLAW_DATA_DIR"] = original_workspace_env
+
+ @staticmethod
+ def test_workspace_priority_over_home():
+ """Test JIUWENCLAW_DATA_DIR takes priority over JIUWENCLAW_HOME for workspace."""
+ # Reset both caches - _workspace_base_dir is used by get_user_workspace_dir
+ setattr(utils, '_workspace_base_dir', None)
+ setattr(utils, '_user_home', None)
+ original_home_env = os.environ.pop("JIUWENCLAW_HOME", None)
+ original_workspace_env = os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+
+ try:
+ # Set both env vars
+ os.environ["JIUWENCLAW_HOME"] = "/home/a"
+ os.environ["JIUWENCLAW_DATA_DIR"] = "/workspace/b"
+
+ # Workspace should use JIUWENCLAW_DATA_DIR directly, not derive from HOME
+ workspace = utils.get_user_workspace_dir()
+ assert workspace == Path("/workspace/b")
+ finally:
+ setattr(utils, '_workspace_base_dir', None)
+ setattr(utils, '_user_home', None)
+ os.environ.pop("JIUWENCLAW_HOME", None)
+ os.environ.pop("JIUWENCLAW_DATA_DIR", None)
+ if original_home_env:
+ os.environ["JIUWENCLAW_HOME"] = original_home_env
+ if original_workspace_env:
+ os.environ["JIUWENCLAW_DATA_DIR"] = original_workspace_env
+
+
+class TestHardcodedPathsPhase2:
+ """Test that hardcoded paths are fixed to use getter functions (Phase 2).
+
+ All assertions use absolute path strings for easy observation.
+ """
+
+ @staticmethod
+ def test_cron_tools_path_equivalence():
+ """Test cron_tools.py path matches expected structure (cross-platform)."""
+ from jiuwenclaw.utils import get_agent_home_dir, get_user_workspace_dir
+
+ # Original hardcoded: get_user_workspace_dir() / "agent" / "home" / "cron_jobs.json"
+ # New: get_agent_home_dir() / "cron_jobs.json"
+ # get_agent_home_dir() = get_user_workspace_dir() / "agent" / "home"
+
+ workspace = get_user_workspace_dir()
+ expected_path = workspace / "agent" / "home" / "cron_jobs.json"
+ actual_path = get_agent_home_dir() / "cron_jobs.json"
+
+ assert str(actual_path.resolve()) == str(expected_path.resolve()), \
+ f"Expected: {expected_path.resolve()}, Got: {actual_path.resolve()}"
+
+ @staticmethod
+ def test_task_tools_path_structure():
+ """Test task_tools.py path uses jiuwenclaw_workspace (migrated from legacy workspace)."""
+ # Reset caches to ensure clean state after previous tests
+ setattr(utils, '_user_home', None)
+ setattr(utils, '_initialized', False)
+ setattr(utils, '_config_dir', None)
+ setattr(utils, '_workspace_dir', None)
+ setattr(utils, '_root_dir', None)
+
+ from jiuwenclaw.agentserver.tools.task_tools import _get_task_data_path
+ from jiuwenclaw.utils import get_user_workspace_dir
+
+ workspace = get_user_workspace_dir()
+ expected_path = workspace / "agent" / "jiuwenclaw_workspace" / "task-data.json"
+ actual_path = Path(_get_task_data_path())
+
+ assert str(actual_path.resolve()) == str(expected_path.resolve()), \
+ f"Expected: {expected_path.resolve()}, Got: {actual_path.resolve()}"
+
+ @staticmethod
+ def test_im_inbound_path_structure():
+ """Test im_inbound.py uses DeepAgent standard USER.md path."""
+ # Reset caches to ensure clean state after previous tests
+ setattr(utils, '_user_home', None)
+ setattr(utils, '_initialized', False)
+ setattr(utils, '_config_dir', None)
+ setattr(utils, '_workspace_dir', None)
+ setattr(utils, '_root_dir', None)
+
+ from jiuwenclaw.utils import get_deepagent_user_md_path, get_user_workspace_dir
+
+ workspace = get_user_workspace_dir()
+ expected_path = workspace / "agent" / "jiuwenclaw_workspace" / "USER.md"
+ actual_path = get_deepagent_user_md_path()
+
+ assert str(actual_path.resolve()) == str(expected_path.resolve()), \
+ f"Expected: {expected_path.resolve()}, Got: {actual_path.resolve()}"
+
+
+class TestAdditionalHardcodedPaths:
+ """Test additional hardcoded paths fixed in config.py and rail_manager.py.
+
+ All assertions use absolute path strings for easy observation.
+ """
+
+ @staticmethod
+ def test_rail_manager_path_structure():
+ """Test rail_manager.py uses get_agent_workspace_dir() for extensions path."""
+ from jiuwenclaw.agentserver.extensions.rail_manager import RailManager
+ from jiuwenclaw.utils import get_user_workspace_dir
+
+ workspace = get_user_workspace_dir()
+ expected_path = workspace / "agent" / "jiuwenclaw_workspace" / "extensions"
+ rail_manager = RailManager()
+
+ extensions_dir = getattr(rail_manager, '_extensions_dir')
+ assert str(extensions_dir.resolve()) == str(expected_path.resolve()), \
+ f"Expected: {expected_path.resolve()}, Got: {extensions_dir.resolve()}"
+
+ @staticmethod
+ def test_config_module_dir_structure():
+ """Test config.py _CONFIG_MODULE_DIR uses get_config_dir()."""
+ from jiuwenclaw.config import _CONFIG_MODULE_DIR
+ from jiuwenclaw.utils import get_config_dir
+
+ config_dir = get_config_dir()
+ expected_path = config_dir
+
+ # Use absolute path comparison
+ assert str(_CONFIG_MODULE_DIR.resolve()) == str(expected_path.resolve()), \
+ f"Expected: {expected_path.resolve()}, Got: {_CONFIG_MODULE_DIR.resolve()}"
+
+
\ No newline at end of file